|
| 1 | +// @vitest-environment jsdom |
| 2 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' |
| 3 | +import { frappeRequest } from './frappeRequest' |
| 4 | +import { setConfig } from './config' |
| 5 | + |
| 6 | +function mockFetch() { |
| 7 | + const fetchMock = vi.fn(async () => ({ |
| 8 | + ok: true, |
| 9 | + json: async () => ({ message: 'ok' }), |
| 10 | + })) |
| 11 | + vi.stubGlobal('fetch', fetchMock) |
| 12 | + return fetchMock |
| 13 | +} |
| 14 | + |
| 15 | +describe('frappeRequest configurable base url and auth headers', () => { |
| 16 | + beforeEach(() => { |
| 17 | + setConfig('requestBaseUrl', undefined) |
| 18 | + setConfig('requestHeaders', undefined) |
| 19 | + }) |
| 20 | + |
| 21 | + afterEach(() => { |
| 22 | + vi.unstubAllGlobals() |
| 23 | + setConfig('requestBaseUrl', undefined) |
| 24 | + setConfig('requestHeaders', undefined) |
| 25 | + }) |
| 26 | + |
| 27 | + it('keeps default behavior when nothing is configured', async () => { |
| 28 | + const fetchMock = mockFetch() |
| 29 | + await frappeRequest({ url: 'ping' }) |
| 30 | + |
| 31 | + const [url, opts] = fetchMock.mock.calls[0] |
| 32 | + expect(url).toBe('/api/method/ping') |
| 33 | + expect(opts.credentials).toBeUndefined() |
| 34 | + expect(opts.headers.Authorization).toBeUndefined() |
| 35 | + }) |
| 36 | + |
| 37 | + it('prepends the configured base url and includes credentials', async () => { |
| 38 | + setConfig('requestBaseUrl', 'https://remote.frappe.test/') |
| 39 | + const fetchMock = mockFetch() |
| 40 | + await frappeRequest({ url: 'ping' }) |
| 41 | + |
| 42 | + const [url, opts] = fetchMock.mock.calls[0] |
| 43 | + expect(url).toBe('https://remote.frappe.test/api/method/ping') |
| 44 | + expect(opts.credentials).toBe('include') |
| 45 | + }) |
| 46 | + |
| 47 | + it('injects static headers from config', async () => { |
| 48 | + setConfig('requestHeaders', { Authorization: 'token key:secret' }) |
| 49 | + const fetchMock = mockFetch() |
| 50 | + await frappeRequest({ url: 'ping' }) |
| 51 | + |
| 52 | + const [, opts] = fetchMock.mock.calls[0] |
| 53 | + expect(opts.headers.Authorization).toBe('token key:secret') |
| 54 | + }) |
| 55 | + |
| 56 | + it('injects headers from a function returning headers', async () => { |
| 57 | + setConfig('requestHeaders', () => ({ Authorization: 'token dynamic:value' })) |
| 58 | + const fetchMock = mockFetch() |
| 59 | + await frappeRequest({ url: 'ping' }) |
| 60 | + |
| 61 | + const [, opts] = fetchMock.mock.calls[0] |
| 62 | + expect(opts.headers.Authorization).toBe('token dynamic:value') |
| 63 | + }) |
| 64 | +}) |
0 commit comments