mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
chore(api): add test utilities (#50289)
This commit is contained in:
committed by
GitHub
parent
f5509d7ba4
commit
c2cb818f87
+62
-4
@@ -7,10 +7,68 @@ declare global {
|
||||
var fastifyTestInstance: Awaited<ReturnType<typeof build>> | undefined;
|
||||
}
|
||||
|
||||
export function superGet(endpoint: string): request.Test {
|
||||
return request(fastifyTestInstance?.server)
|
||||
.get(endpoint)
|
||||
.set('Origin', 'https://www.freecodecamp.org');
|
||||
type Options = {
|
||||
sendCSRFToken: boolean;
|
||||
};
|
||||
|
||||
// TODO: remove this function and use superRequest instead
|
||||
export function superPut(
|
||||
resource: string,
|
||||
setCookies: string[],
|
||||
opts?: Options
|
||||
): request.Test {
|
||||
return superRequest(
|
||||
resource,
|
||||
{
|
||||
method: 'PUT',
|
||||
setCookies
|
||||
},
|
||||
opts
|
||||
);
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const requests = {
|
||||
GET: (resource: string) => request(fastifyTestInstance?.server).get(resource),
|
||||
POST: (resource: string) =>
|
||||
request(fastifyTestInstance?.server).post(resource),
|
||||
PUT: (resource: string) => request(fastifyTestInstance?.server).put(resource)
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export const getCsrfToken = (setCookies: string[]): string | undefined => {
|
||||
const csrfSetCookie = setCookies.find(str => str.includes('csrf_token'));
|
||||
const [csrfCookie] = csrfSetCookie?.split(';') ?? [];
|
||||
const [_key, csrfToken] = csrfCookie?.split('=') ?? [];
|
||||
|
||||
return csrfToken;
|
||||
};
|
||||
|
||||
export function superRequest(
|
||||
resource: string,
|
||||
config: {
|
||||
method: 'GET' | 'POST' | 'PUT';
|
||||
setCookies?: string[];
|
||||
},
|
||||
options?: Options
|
||||
): request.Test {
|
||||
const { method, setCookies } = config;
|
||||
const { sendCSRFToken = true } = options ?? {};
|
||||
|
||||
const req = requests[method](resource).set(
|
||||
'Origin',
|
||||
'https://www.freecodecamp.org'
|
||||
);
|
||||
|
||||
if (setCookies) {
|
||||
void req.set('Cookie', setCookies);
|
||||
}
|
||||
|
||||
const csrfToken = (setCookies && getCsrfToken(setCookies)) ?? '';
|
||||
if (sendCSRFToken) {
|
||||
void req.set('CSRF-Token', csrfToken);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
export function setupServer(): void {
|
||||
|
||||
Reference in New Issue
Block a user