forked from AubaidFarrukh/smart-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegrations.test.ts
More file actions
274 lines (216 loc) · 9.08 KB
/
Copy pathintegrations.test.ts
File metadata and controls
274 lines (216 loc) · 9.08 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { AxiosRetry, FetchRetry } from '../src/integrations';
import fs from 'fs';
import path from 'path';
import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
const TEST_LOG_PATH = path.join(__dirname, 'fetch-retry-test.json');
const AXIOS_TEST_LOG_PATH = path.join(__dirname, 'axios-retry-test.json');
describe('FetchRetry body serialization', () => {
let fetchRetry: FetchRetry;
let fetchMock: jest.Mock;
const originalFetch = global.fetch;
beforeEach(() => {
if (fs.existsSync(TEST_LOG_PATH)) {
fs.unlinkSync(TEST_LOG_PATH);
}
fetchRetry = new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH);
fetchMock = jest.fn().mockResolvedValue(new Response(null, { status: 200 }));
global.fetch = fetchMock as unknown as typeof fetch;
});
afterEach(() => {
global.fetch = originalFetch;
if (fs.existsSync(TEST_LOG_PATH)) {
fs.unlinkSync(TEST_LOG_PATH);
}
});
it('JSON-stringifies plain object bodies and sets Content-Type', async () => {
await fetchRetry.post('/data', { hello: 'world' });
const [, init] = fetchMock.mock.calls[0];
expect(init.body).toBe(JSON.stringify({ hello: 'world' }));
expect(init.headers).toMatchObject({ 'Content-Type': 'application/json' });
});
it('passes FormData through untouched without forcing Content-Type', async () => {
const form = new FormData();
form.append('file', 'contents');
await fetchRetry.post('/upload', form);
const [, init] = fetchMock.mock.calls[0];
expect(init.body).toBe(form);
expect(init.headers).toBeUndefined();
});
it('passes URLSearchParams through untouched', async () => {
const params = new URLSearchParams({ a: '1' });
await fetchRetry.post('/form', params);
const [, init] = fetchMock.mock.calls[0];
expect(init.body).toBe(params);
});
it('passes an already-serialized string body through untouched', async () => {
const raw = '{"already":"json"}';
await fetchRetry.post('/raw', raw);
const [, init] = fetchMock.mock.calls[0];
expect(init.body).toBe(raw);
expect(init.headers).toBeUndefined();
});
it('does not force a body or Content-Type when none is provided', async () => {
await fetchRetry.delete('/thing');
const [, init] = fetchMock.mock.calls[0];
expect(init.body).toBeUndefined();
expect(init.headers).toBeUndefined();
});
it('applies the same handling for put and patch', async () => {
const form = new FormData();
await fetchRetry.put('/upload', form);
let [, init] = fetchMock.mock.calls[0];
expect(init.body).toBe(form);
await fetchRetry.patch('/data', { hello: 'world' });
[, init] = fetchMock.mock.calls[1];
expect(init.body).toBe(JSON.stringify({ hello: 'world' }));
expect(init.headers).toMatchObject({ 'Content-Type': 'application/json' });
});
});
describe('FetchRetry failure logging', () => {
let fetchMock: jest.Mock;
const originalFetch = global.fetch;
beforeEach(() => {
if (fs.existsSync(TEST_LOG_PATH)) {
fs.unlinkSync(TEST_LOG_PATH);
}
});
afterEach(() => {
global.fetch = originalFetch;
if (fs.existsSync(TEST_LOG_PATH)) {
fs.unlinkSync(TEST_LOG_PATH);
}
});
it('records the real url, method, headers, and body for a failed POST', async () => {
fetchMock = jest.fn().mockResolvedValue(new Response(null, { status: 500 }));
global.fetch = fetchMock as unknown as typeof fetch;
const fetchRetry = new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH);
await expect(fetchRetry.post('/orders', { id: 1 })).rejects.toThrow();
const [failure] = await fetchRetry.getRetryManager().getFailedRequests();
expect(failure.url).toBe('/orders');
expect(failure.method).toBe('POST');
expect(failure.headers).toMatchObject({ 'content-type': 'application/json' });
expect(failure.body).toBe(JSON.stringify({ id: 1 }));
expect(failure.statusCode).toBe(500);
});
it('records the real url and method for a failed DELETE', async () => {
fetchMock = jest.fn().mockResolvedValue(new Response(null, { status: 503 }));
global.fetch = fetchMock as unknown as typeof fetch;
const fetchRetry = new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH);
await expect(fetchRetry.delete('/orders/1')).rejects.toThrow();
const [failure] = await fetchRetry.getRetryManager().getFailedRequests();
expect(failure.url).toBe('/orders/1');
expect(failure.method).toBe('DELETE');
});
it('records the url and method even when fetch itself throws a network error', async () => {
fetchMock = jest.fn().mockRejectedValue(new TypeError('fetch failed'));
global.fetch = fetchMock as unknown as typeof fetch;
const fetchRetry = new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH);
await expect(fetchRetry.get('/status')).rejects.toThrow('fetch failed');
const [failure] = await fetchRetry.getRetryManager().getFailedRequests();
expect(failure.url).toBe('/status');
expect(failure.method).toBe('GET');
expect(failure.error).toBe('fetch failed');
});
it('does not crash on construction or use when the filesystem is unavailable', async () => {
fetchMock = jest.fn().mockResolvedValue(new Response(null, { status: 200 }));
global.fetch = fetchMock as unknown as typeof fetch;
const existsSyncSpy = jest.spyOn(fs, 'existsSync').mockImplementation(() => {
throw new Error('fs unavailable');
});
const writeFileSyncSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => {
throw new Error('fs unavailable');
});
try {
expect(() => new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH)).not.toThrow();
const unusableFsRetry = new FetchRetry({ maxRetries: 1 }, TEST_LOG_PATH);
const response = await unusableFsRetry.get('/status');
expect(response.status).toBe(200);
} finally {
existsSyncSpy.mockRestore();
writeFileSyncSpy.mockRestore();
}
});
});
describe('AxiosRetry', () => {
let axiosRetry: AxiosRetry;
beforeEach(() => {
if (fs.existsSync(AXIOS_TEST_LOG_PATH)) {
fs.unlinkSync(AXIOS_TEST_LOG_PATH);
}
mockedAxios.request = jest.fn();
axiosRetry = new AxiosRetry({ maxRetries: 1 }, AXIOS_TEST_LOG_PATH);
});
afterEach(() => {
if (fs.existsSync(AXIOS_TEST_LOG_PATH)) {
fs.unlinkSync(AXIOS_TEST_LOG_PATH);
}
});
it('resolves with the axios response on a successful request', async () => {
const response = { data: { hello: 'world' }, status: 200 };
mockedAxios.request.mockResolvedValue(response);
const result = await axiosRetry.get('/data');
expect(result).toBe(response);
});
it('passes the right method, url, and data through to axios.request for get/post/put/delete/patch', async () => {
mockedAxios.request.mockResolvedValue({ data: null, status: 200 });
await axiosRetry.get('/items');
expect(mockedAxios.request).toHaveBeenLastCalledWith({ method: 'GET', url: '/items' });
await axiosRetry.post('/items', { name: 'a' });
expect(mockedAxios.request).toHaveBeenLastCalledWith({
method: 'POST',
url: '/items',
data: { name: 'a' },
});
await axiosRetry.put('/items/1', { name: 'b' });
expect(mockedAxios.request).toHaveBeenLastCalledWith({
method: 'PUT',
url: '/items/1',
data: { name: 'b' },
});
await axiosRetry.delete('/items/1');
expect(mockedAxios.request).toHaveBeenLastCalledWith({ method: 'DELETE', url: '/items/1' });
await axiosRetry.patch('/items/1', { name: 'c' });
expect(mockedAxios.request).toHaveBeenLastCalledWith({
method: 'PATCH',
url: '/items/1',
data: { name: 'c' },
});
});
it('retries per RetryConfig and eventually throws when every attempt fails', async () => {
const error: any = new Error('Request failed with status code 500');
error.response = { status: 500, statusText: 'Internal Server Error' };
error.config = {
url: '/orders',
method: 'post',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ id: 1 }),
};
mockedAxios.request.mockRejectedValue(error);
const retryingAxios = new AxiosRetry(
{ maxRetries: 3, delay: 0, idempotent: true },
AXIOS_TEST_LOG_PATH
);
await expect(retryingAxios.post('/orders', { id: 1 })).rejects.toThrow(
'Request failed with status code 500'
);
expect(mockedAxios.request).toHaveBeenCalledTimes(3);
});
it('logs a failed request via getRetryManager().getFailedRequests() once retries are exhausted', async () => {
const error: any = new Error('Request failed with status code 500');
error.response = { status: 500, statusText: 'Internal Server Error' };
error.config = {
url: '/orders',
method: 'post',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ id: 1 }),
};
mockedAxios.request.mockRejectedValue(error);
await expect(axiosRetry.post('/orders', { id: 1 })).rejects.toThrow();
const [failure] = await axiosRetry.getRetryManager().getFailedRequests();
expect(failure.url).toBe('/orders');
expect(failure.method).toBe('POST');
expect(failure.statusCode).toBe(500);
});
});