Skip to content

Commit d94672a

Browse files
committed
✅ (frontend) Add test for utils.ts
Signed-off-by: Zorin95670 <moittie.vincent@gmail.com>
1 parent 25b1003 commit d94672a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { errorCauses, getCSRFToken } from '@/api';
2+
3+
describe('utils', () => {
4+
describe('errorCauses', () => {
5+
const createMockResponse = (jsonData: any, status = 400): Response => {
6+
return {
7+
status,
8+
json: () => jsonData,
9+
} as unknown as Response;
10+
};
11+
12+
it('parses multiple string causes from error body', async () => {
13+
const mockResponse = createMockResponse(
14+
{
15+
field: ['error message 1', 'error message 2'],
16+
},
17+
400,
18+
);
19+
20+
const result = await errorCauses(mockResponse, { context: 'login' });
21+
22+
expect(result.status).toBe(400);
23+
expect(result.cause).toEqual(['error message 1', 'error message 2']);
24+
expect(result.data).toEqual({ context: 'login' });
25+
});
26+
27+
it('returns undefined causes if no JSON body', async () => {
28+
const mockResponse = createMockResponse(null, 500);
29+
30+
const result = await errorCauses(mockResponse);
31+
32+
expect(result.status).toBe(500);
33+
expect(result.cause).toBeUndefined();
34+
expect(result.data).toBeUndefined();
35+
});
36+
});
37+
38+
describe('getCSRFToken', () => {
39+
it('extracts csrftoken from document.cookie', () => {
40+
Object.defineProperty(document, 'cookie', {
41+
writable: true,
42+
value: 'sessionid=xyz; csrftoken=abc123; theme=dark',
43+
});
44+
45+
expect(getCSRFToken()).toBe('abc123');
46+
});
47+
48+
it('returns undefined if csrftoken is not present', () => {
49+
Object.defineProperty(document, 'cookie', {
50+
writable: true,
51+
value: 'sessionid=xyz; theme=dark',
52+
});
53+
54+
expect(getCSRFToken()).toBeUndefined();
55+
});
56+
});
57+
});

0 commit comments

Comments
 (0)