aboutsummaryrefslogtreecommitdiffstats
path: root/frontend-vanilla/src/api.test.ts
blob: 9128ef37884ddbb2fb15eef5838b163a6ee29903 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { apiFetch, getCookie } from './api';

describe('api', () => {
    beforeEach(() => {
        vi.stubGlobal('fetch', vi.fn());
        document.cookie = '';
    });

    it('getCookie should return cookie value', () => {
        document.cookie = 'foo=bar';
        document.cookie = 'csrf_token=test-token';
        expect(getCookie('csrf_token')).toBe('test-token');
        expect(getCookie('foo')).toBe('bar');
        expect(getCookie('baz')).toBeUndefined();
    });

    it('apiFetch should include CSRF token for POST requests', async () => {
        document.cookie = 'csrf_token=test-token';
        const mockFetch = vi.mocked(fetch);
        mockFetch.mockResolvedValueOnce(new Response());

        await apiFetch('/test', { method: 'POST' });

        expect(mockFetch).toHaveBeenCalledWith('/test', expect.objectContaining({
            method: 'POST',
            headers: expect.any(Headers),
            credentials: 'include'
        }));

        const headers = mockFetch.mock.calls[0][1]?.headers as Headers;
        expect(headers.get('X-CSRF-Token')).toBe('test-token');
    });

    it('apiFetch should not include CSRF token for GET requests', async () => {
        document.cookie = 'csrf_token=test-token';
        const mockFetch = vi.mocked(fetch);
        mockFetch.mockResolvedValueOnce(new Response());

        await apiFetch('/test');

        const headers = mockFetch.mock.calls[0][1]?.headers as Headers;
        expect(headers.get('X-CSRF-Token')).toBeNull();
    });
});