-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathfetch.test.ts
More file actions
176 lines (155 loc) · 5.43 KB
/
Copy pathfetch.test.ts
File metadata and controls
176 lines (155 loc) · 5.43 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { AmplifyErrorCode } from '../../src/types';
import { fetchTransferHandler } from '../../src/clients/handlers/fetch';
describe(fetchTransferHandler.name, () => {
const mockBody = {
text: jest.fn(),
blob: jest.fn(),
json: jest.fn(),
};
const mockFetchResponse = Object.assign(
{
status: 200,
headers: { forEach: jest.fn() },
body: {},
},
mockBody,
);
const mockRequest = {
method: 'GET' as const,
headers: {},
url: new URL('https://foo.bar'),
};
const mockPayloadValue = 'payload value';
const mockFetch = jest.fn();
beforeAll(() => {
(global as any).fetch = mockFetch;
});
beforeEach(() => {
jest.clearAllMocks();
mockFetch.mockResolvedValue(mockFetchResponse);
});
it('should support abort signal', async () => {
const { signal } = new AbortController();
await fetchTransferHandler(mockRequest, { abortSignal: signal });
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1]).toEqual(
expect.objectContaining({ signal }),
);
});
it('should configure cache', async () => {
const cacheMode = 'no-store';
await fetchTransferHandler(mockRequest, { cache: cacheMode });
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1]).toEqual(
expect.objectContaining({ cache: cacheMode }),
);
});
it('should set credentials options to "include" if cross domain credentials is set', async () => {
await fetchTransferHandler(mockRequest, {
withCrossDomainCredentials: true,
});
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1]).toEqual(
expect.objectContaining({ credentials: 'include' }),
);
});
it('should set credentials options to "same-origin" if cross domain credentials is not set', async () => {
await fetchTransferHandler(mockRequest, {});
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1]).toEqual(
expect.objectContaining({ credentials: 'same-origin' }),
);
});
it('should support headers', async () => {
mockFetchResponse.headers.forEach.mockImplementation((callback: any) => {
callback('foo', 'bar');
});
const { headers } = await fetchTransferHandler(mockRequest, {});
expect(headers).toEqual({ bar: 'foo' });
});
it('should support text() in response.body with caching', async () => {
mockBody.text.mockResolvedValue(mockPayloadValue);
const { body } = await fetchTransferHandler(mockRequest, {});
if (!body) {
fail('body should exist');
}
expect(await body.text()).toBe(mockPayloadValue);
expect(await body.text()).toBe(mockPayloadValue);
expect(mockBody.text).toHaveBeenCalledTimes(1); // test caching
});
it('should support blob() in response.body with caching', async () => {
mockBody.blob.mockResolvedValue(mockPayloadValue);
const { body } = await fetchTransferHandler(mockRequest, {});
if (!body) {
fail('body should exist');
}
expect(await body.blob()).toBe(mockPayloadValue);
expect(await body.blob()).toBe(mockPayloadValue);
expect(mockBody.blob).toHaveBeenCalledTimes(1); // test caching
});
it('should support json() in response.body with caching', async () => {
mockBody.json.mockResolvedValue(mockPayloadValue);
const { body } = await fetchTransferHandler(mockRequest, {});
if (!body) {
fail('body should exist');
}
expect(await body.json()).toBe(mockPayloadValue);
expect(await body.json()).toBe(mockPayloadValue);
expect(mockBody.json).toHaveBeenCalledTimes(1); // test caching
});
test.each(['GET', 'HEAD'])(
'should ignore request payload for %s request',
async method => {
await fetchTransferHandler(
{ ...mockRequest, method, body: 'Mock Body' },
{},
);
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1].body).toBeUndefined();
},
);
test.each(['POST', 'PUT', 'DELETE', 'PATCH'])(
'should include request payload for %s request',
async method => {
await fetchTransferHandler(
{ ...mockRequest, method, body: 'Mock Body' },
{},
);
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch.mock.calls[0][1].body).toBe('Mock Body');
},
);
it('should throw NetworkError when fetch rejects with TypeError (browser)', async () => {
mockFetch.mockRejectedValue(new TypeError('Failed to fetch'));
await expect(fetchTransferHandler(mockRequest, {})).rejects.toMatchObject({
name: AmplifyErrorCode.NetworkError,
message: 'A network error has occurred.',
underlyingError: expect.any(TypeError),
});
});
it('should throw NetworkError when fetch rejects with plain Error (React Native native network failure)', async () => {
mockFetch.mockRejectedValue(new Error('Network request failed'));
await expect(fetchTransferHandler(mockRequest, {})).rejects.toMatchObject({
name: AmplifyErrorCode.NetworkError,
message: 'A network error has occurred.',
underlyingError: expect.any(Error),
});
});
it('should rethrow AbortError without wrapping', async () => {
const abortError = Object.assign(new Error('The user aborted a request.'), {
name: 'AbortError',
});
mockFetch.mockRejectedValue(abortError);
await expect(fetchTransferHandler(mockRequest, {})).rejects.toBe(
abortError,
);
});
it('should include the original error as underlyingError', async () => {
const cause = new Error('Network request failed');
mockFetch.mockRejectedValue(cause);
await expect(fetchTransferHandler(mockRequest, {})).rejects.toMatchObject({
name: AmplifyErrorCode.NetworkError,
underlyingError: cause,
});
});
});