test: minor fix to how cookies are passed around (#55259)

This commit is contained in:
Oliver Eyton-Williams
2024-06-21 17:36:46 +02:00
committed by GitHub
parent dda9c929b0
commit fd1bf0dd5a
2 changed files with 24 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
import { getCsrfToken } from './jest.utils';
import { getCsrfToken, getCookies } from './jest.utils';
const fakeCookies = [
'_csrf=123; Path=/; HttpOnly; SameSite=Strict',
@@ -17,3 +17,18 @@ describe('getCsrfToken', () => {
).toBeUndefined();
});
});
describe('setCookiesToCookies', () => {
test('returns a string of cookies', () => {
expect(getCookies(fakeCookies)).toEqual(
'_csrf=123; csrf_token=abc-123; sessionId=CV-abc.123'
);
});
test('handles bare cookies', () => {
expect(getCookies(['_csrf=123'])).toEqual('_csrf=123');
});
test('throws an error if the cookies are malformed', () => {
expect(() => getCookies(['_csrf'])).toThrow();
});
});

View File

@@ -34,6 +34,13 @@ export const getCsrfToken = (setCookies: string[]): string | undefined => {
export const ORIGIN = 'https://www.freecodecamp.org';
export const getCookies = (setCookies: string[]): string => {
for (const cookie of setCookies) {
expect(cookie).toMatch(/.*=.*/);
}
return setCookies.map(cookie => cookie.split(';')[0]).join('; ');
};
export function superRequest(
resource: string,
config: {
@@ -48,7 +55,7 @@ export function superRequest(
const req = requests[method](resource).set('Origin', ORIGIN);
if (setCookies) {
void req.set('Cookie', setCookies);
void req.set('Cookie', getCookies(setCookies));
}
const csrfToken = (setCookies && getCsrfToken(setCookies)) ?? '';