diff --git a/api/jest.utils.ts b/api/jest.utils.ts index f15eef95fa1..97b508f50da 100644 --- a/api/jest.utils.ts +++ b/api/jest.utils.ts @@ -13,7 +13,7 @@ declare global { type Options = { sendCSRFToken?: boolean; -} & Record; +}; const requests = { GET: (resource: string) => request(fastifyTestInstance?.server).get(resource), @@ -41,16 +41,27 @@ export const getCookies = (setCookies: string[]): string => { return setCookies.map(cookie => cookie.split(';')[0]).join('; '); }; +/** + * A wrapper around supertest that handles common setup for requests. Namely + * setting the Origin header, cookies and CSRF token. + * + * @param resource - The URL of the resource to be requested + * @param config - The configuration for the request + * @param config.method - The HTTP method to be used + * @param config.setCookies - The cookies to be set in the request + * @param options - Additional options for the request + * @param options.sendCSRFToken - Whether to send the CSRF token in the request (default: true) + * @returns The request object + */ export function superRequest( resource: string, config: { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; setCookies?: string[]; - headers?: { referer: string }; }, options?: Options ): request.Test { - const { method, setCookies, headers } = config; + const { method, setCookies } = config; const { sendCSRFToken = true } = options ?? {}; const req = requests[method](resource).set('Origin', ORIGIN); @@ -59,10 +70,6 @@ export function superRequest( void req.set('Cookie', getCookies(setCookies)); } - if (headers) { - void req.set('Referer', headers.referer); - } - const csrfToken = (setCookies && getCsrfToken(setCookies)) ?? ''; if (sendCSRFToken) { void req.set('CSRF-Token', csrfToken); @@ -70,6 +77,15 @@ export function superRequest( return req; } +/** + * Factory function for 'superRequest' allows for the creation of a concise + * request function with the desired method and setCookies baked in. + * + * @param config + * @param config.method - HTTP method + * @param config.setCookies - Cookies to be set in the request + * @returns A superRequest function with the desired method and setCookies + */ export function createSuperRequest(config: { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; setCookies?: string[]; diff --git a/api/src/routes/settings.test.ts b/api/src/routes/settings.test.ts index 23aa8abc70c..12603ed0bd7 100644 --- a/api/src/routes/settings.test.ts +++ b/api/src/routes/settings.test.ts @@ -1029,9 +1029,8 @@ Happy coding! describe('/confirm-email', () => { it('redirects to the HOME_LOCATION with flash message', async () => { const res = await superRequest('/confirm-email', { - method: 'GET', - headers: { referer: 'https://who.knows/' } - }); + method: 'GET' + }).set('Referer', 'https://who.knows/'); expect(res.status).toBe(302); expect(res.headers).toMatchObject({