Skip to content

Commit ab68e2e

Browse files
committed
test: add fetch util tests
1 parent 4822611 commit ab68e2e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import fetchMock from 'jest-fetch-mock';
2+
import { createApiKeyMiddleware, createFetchFn, FetchMiddleware, RequestContext } from '../src';
3+
4+
describe('fetch middleware', () => {
5+
test('createApiKeyMiddleware adds x-api-key header to correct host request', async () => {
6+
const apiKey = 'MY_KEY';
7+
8+
const middleware = createApiKeyMiddleware({ apiKey });
9+
expect(middleware.pre).not.toBeNull();
10+
11+
const fetchFn = createFetchFn(middleware);
12+
13+
await fetchFn('https://example.com');
14+
expect(fetchMock.mock.calls[0][1]?.headers).toBe(undefined);
15+
16+
await fetchFn('https://api.stacks.co');
17+
expect(fetchMock.mock.calls[1][1]?.headers).toBeDefined();
18+
expect((fetchMock.mock.calls[1][1]?.headers as Headers)?.get('x-api-key')).toContain(apiKey);
19+
});
20+
21+
test('middleware calls pre and post', async () => {
22+
const preMiddleware = jest.fn(() => undefined as void);
23+
const postMiddleware = jest.fn(() => undefined as void);
24+
25+
const middleware = {
26+
pre: preMiddleware,
27+
post: postMiddleware,
28+
} as FetchMiddleware;
29+
30+
const fetchFn = createFetchFn(middleware);
31+
await fetchFn('https://example.com');
32+
33+
expect(preMiddleware.mock.calls.length).toBe(1);
34+
expect(postMiddleware.mock.calls.length).toBe(1);
35+
});
36+
37+
test.each(['pre', 'post'])('middleware chains pass state', async hook => {
38+
const middleware1 = jest.fn((ctx: RequestContext) => {
39+
ctx.init.headers = new Headers();
40+
ctx.init.headers.set('foo', 'bar');
41+
return ctx;
42+
});
43+
const middleware2 = jest.fn((ctx: RequestContext) => {
44+
expect((ctx.init.headers as Headers).get('foo')).toBe('bar');
45+
(ctx.init.headers as Headers).set('foo', 'bla');
46+
// should also work if middleware doesn't return context
47+
});
48+
const middleware3 = jest.fn((ctx: RequestContext) => {
49+
expect((ctx.init.headers as Headers).get('foo')).toBe('bla');
50+
(ctx.init.headers as Headers).set('foo', 'baz');
51+
return ctx;
52+
});
53+
54+
const fetchFn = createFetchFn(
55+
{
56+
[hook]: middleware1,
57+
},
58+
{
59+
[hook]: middleware2,
60+
},
61+
{
62+
[hook]: middleware3,
63+
}
64+
);
65+
66+
fetchMock.mockOnce('*', { status: 200 });
67+
const res = await fetchFn('https://httpstat.us/202');
68+
console.log(res);
69+
70+
expect((fetchMock.mock.calls[0][1]?.headers as Headers).get('foo')).toBe('baz');
71+
72+
expect(middleware1.mock.calls.length).toBe(1);
73+
expect(middleware2.mock.calls.length).toBe(1);
74+
expect(middleware3.mock.calls.length).toBe(1);
75+
});
76+
});

0 commit comments

Comments
 (0)