-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.test.ts
More file actions
95 lines (73 loc) · 2.7 KB
/
fetch.test.ts
File metadata and controls
95 lines (73 loc) · 2.7 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* eslint-disable no-new */
import { abortSignalAny } from '../abort-signal-any';
jest.mock('../abort-signal-any', () => ({
abortSignalAny: jest.fn((...signals) => signals[0] || signals[1])
}));
describe('Fetch lib', () => {
let injectAborterContextIntoHttpRequest;
let internalFetch;
let mockFetch;
let mockAborter;
let originalFetchRef;
beforeAll(async () => {
mockFetch = jest.fn().mockResolvedValue({ ok: true });
globalThis.fetch = mockFetch;
originalFetchRef = globalThis.fetch;
const module = await import('./fetch.lib');
injectAborterContextIntoHttpRequest = module.injectAborterContextIntoHttpRequest;
internalFetch = module.internalFetch;
module.setAborterContextProvisionMode(true);
});
beforeEach(() => {
mockFetch.mockClear();
mockFetch.mockResolvedValue({ ok: true });
mockAborter = {
signal: { aborted: false },
requestOptions: { headers: { 'X-Custom': 'from-aborter' } }
};
injectAborterContextIntoHttpRequest(null);
jest.clearAllMocks();
});
afterEach(() => {
globalThis.fetch = originalFetchRef;
});
describe('injectAborterContextIntoHttpRequest', () => {
it('should restore original fetch when passing null and fetch is overridden', () => {
injectAborterContextIntoHttpRequest(mockAborter);
expect(globalThis.fetch).toBe(internalFetch);
injectAborterContextIntoHttpRequest(null);
expect(globalThis.fetch).toBe(originalFetchRef);
});
it('should not restore original fetch if it is already original', () => {
globalThis.fetch = originalFetchRef;
injectAborterContextIntoHttpRequest(null);
expect(globalThis.fetch).toBe(originalFetchRef);
});
});
describe('internalFetch', () => {
it('should call original fetch when no aborter is set', async () => {
injectAborterContextIntoHttpRequest(null);
await internalFetch('localhost');
expect(mockFetch).toHaveBeenCalledWith('localhost', undefined);
});
it('should use aborter signal and headers when aborter exists', async () => {
injectAborterContextIntoHttpRequest(mockAborter);
const init = {
method: 'POST',
headers: { 'X-User': 'test' },
signal: new AbortController().signal
};
await internalFetch('https://example.com', init);
expect(mockFetch).toHaveBeenCalledWith(
'https://example.com',
expect.objectContaining({
method: 'POST',
headers: { 'X-User': 'test', 'X-Custom': 'from-aborter' },
signal: expect.anything()
})
);
expect(abortSignalAny).toHaveBeenCalledWith(init.signal, mockAborter.signal);
expect(globalThis.fetch).toBe(originalFetchRef);
});
});
});