refactor: simplified and documented test helpers (#55493)

This commit is contained in:
Oliver Eyton-Williams
2024-07-13 01:23:37 +02:00
committed by GitHub
parent b45a88d6db
commit 0a99796dd3
2 changed files with 25 additions and 10 deletions
+23 -7
View File
@@ -13,7 +13,7 @@ declare global {
type Options = {
sendCSRFToken?: boolean;
} & Record<string, unknown>;
};
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[];