forked from apache-superset/superset-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallApi.test.ts
566 lines (490 loc) · 19.5 KB
/
callApi.test.ts
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import fetchMock from 'fetch-mock';
import callApi from '../../src/callApi/callApi';
import * as constants from '../../src/constants';
import { LOGIN_GLOB } from '../fixtures/constants';
import { CallApi, JsonObject } from '../../src/types';
import { DEFAULT_FETCH_RETRY_OPTIONS } from '../../src/constants';
describe('callApi()', () => {
beforeAll(() => {
fetchMock.get(LOGIN_GLOB, { csrf_token: '1234' });
});
afterAll(fetchMock.restore);
const mockGetUrl = '/mock/get/url';
const mockPostUrl = '/mock/post/url';
const mockPutUrl = '/mock/put/url';
const mockPatchUrl = '/mock/patch/url';
const mockCacheUrl = '/mock/cache/url';
const mockNotFound = '/mock/notfound';
const mockErrorUrl = '/mock/error/url';
const mock503 = '/mock/503';
const mockGetPayload = { get: 'payload' };
const mockPostPayload = { post: 'payload' };
const mockPutPayload = { post: 'payload' };
const mockPatchPayload = { post: 'payload' };
const mockCachePayload = {
status: 200,
body: 'BODY',
headers: { Etag: 'etag' },
};
const mockErrorPayload = { status: 500, statusText: 'Internal error' };
fetchMock.get(mockGetUrl, mockGetPayload);
fetchMock.post(mockPostUrl, mockPostPayload);
fetchMock.put(mockPutUrl, mockPutPayload);
fetchMock.patch(mockPatchUrl, mockPatchPayload);
fetchMock.get(mockCacheUrl, mockCachePayload);
fetchMock.get(mockNotFound, { status: 404 });
fetchMock.get(mock503, { status: 503 });
fetchMock.get(mockErrorUrl, () => Promise.reject(mockErrorPayload));
afterEach(fetchMock.reset);
describe('request config', () => {
it('calls the right url with the specified method', async () => {
expect.assertions(4);
await Promise.all([
callApi({ url: mockGetUrl, method: 'GET' }),
callApi({ url: mockPostUrl, method: 'POST' }),
callApi({ url: mockPutUrl, method: 'PUT' }),
callApi({ url: mockPatchUrl, method: 'PATCH' }),
]);
expect(fetchMock.calls(mockGetUrl)).toHaveLength(1);
expect(fetchMock.calls(mockPostUrl)).toHaveLength(1);
expect(fetchMock.calls(mockPutUrl)).toHaveLength(1);
expect(fetchMock.calls(mockPatchUrl)).toHaveLength(1);
});
it('passes along mode, cache, credentials, headers, body, signal, and redirect parameters in the request', async () => {
expect.assertions(8);
const mockRequest: CallApi = {
url: mockGetUrl,
mode: 'cors',
cache: 'default',
credentials: 'include',
headers: {
custom: 'header',
},
redirect: 'follow',
signal: undefined,
body: 'BODY',
};
await callApi(mockRequest);
const calls = fetchMock.calls(mockGetUrl);
const fetchParams = calls[0][1];
expect(calls).toHaveLength(1);
expect(fetchParams.mode).toBe(mockRequest.mode);
expect(fetchParams.cache).toBe(mockRequest.cache);
expect(fetchParams.credentials).toBe(mockRequest.credentials);
expect(fetchParams.headers).toEqual(
expect.objectContaining(mockRequest.headers) as typeof fetchParams.headers,
);
expect(fetchParams.redirect).toBe(mockRequest.redirect);
expect(fetchParams.signal).toBe(mockRequest.signal);
expect(fetchParams.body).toBe(mockRequest.body);
});
});
describe('POST requests', () => {
it('encodes key,value pairs from postPayload', async () => {
expect.assertions(3);
const postPayload = { key: 'value', anotherKey: 1237 };
await callApi({ url: mockPostUrl, method: 'POST', postPayload });
const calls = fetchMock.calls(mockPostUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
Object.entries(postPayload).forEach(([key, value]) => {
expect(body.get(key)).toBe(JSON.stringify(value));
});
});
// the reason for this is to omit strings like 'undefined' from making their way to the backend
it('omits key,value pairs from postPayload that have undefined values (POST)', async () => {
expect.assertions(3);
const postPayload = { key: 'value', noValue: undefined };
await callApi({ url: mockPostUrl, method: 'POST', postPayload });
const calls = fetchMock.calls(mockPostUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
expect(body.get('key')).toBe(JSON.stringify(postPayload.key));
expect(body.get('noValue')).toBeNull();
});
it('respects the stringify flag in POST requests', async () => {
const postPayload = {
string: 'value',
number: 1237,
array: [1, 2, 3],
object: { a: 'a', 1: 1 },
null: null,
emptyString: '',
};
expect.assertions(1 + 3 * Object.keys(postPayload).length);
await Promise.all([
callApi({ url: mockPostUrl, method: 'POST', postPayload }),
callApi({ url: mockPostUrl, method: 'POST', postPayload, stringify: false }),
callApi({ url: mockPostUrl, method: 'POST', jsonPayload: postPayload }),
]);
const calls = fetchMock.calls(mockPostUrl);
expect(calls).toHaveLength(3);
const stringified = calls[0][1].body as FormData;
const unstringified = calls[1][1].body as FormData;
const jsonRequestBody = JSON.parse(calls[2][1].body as string) as JsonObject;
Object.entries(postPayload).forEach(([key, value]) => {
expect(stringified.get(key)).toBe(JSON.stringify(value));
expect(unstringified.get(key)).toBe(String(value));
expect(jsonRequestBody[key]).toEqual(value);
});
});
});
describe('PUT requests', () => {
it('encodes key,value pairs from postPayload', async () => {
expect.assertions(3);
const postPayload = { key: 'value', anotherKey: 1237 };
await callApi({ url: mockPutUrl, method: 'PUT', postPayload });
const calls = fetchMock.calls(mockPutUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
Object.entries(postPayload).forEach(([key, value]) => {
expect(body.get(key)).toBe(JSON.stringify(value));
});
});
// the reason for this is to omit strings like 'undefined' from making their way to the backend
it('omits key,value pairs from postPayload that have undefined values (PUT)', async () => {
expect.assertions(3);
const postPayload = { key: 'value', noValue: undefined };
await callApi({ url: mockPutUrl, method: 'PUT', postPayload });
const calls = fetchMock.calls(mockPutUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
expect(body.get('key')).toBe(JSON.stringify(postPayload.key));
expect(body.get('noValue')).toBeNull();
});
it('respects the stringify flag in PUT requests', async () => {
const postPayload = {
string: 'value',
number: 1237,
array: [1, 2, 3],
object: { a: 'a', 1: 1 },
null: null,
emptyString: '',
};
expect.assertions(1 + 2 * Object.keys(postPayload).length);
await Promise.all([
callApi({ url: mockPutUrl, method: 'PUT', postPayload }),
callApi({ url: mockPutUrl, method: 'PUT', postPayload, stringify: false }),
]);
const calls = fetchMock.calls(mockPutUrl);
expect(calls).toHaveLength(2);
const stringified = calls[0][1].body as FormData;
const unstringified = calls[1][1].body as FormData;
Object.entries(postPayload).forEach(([key, value]) => {
expect(stringified.get(key)).toBe(JSON.stringify(value));
expect(unstringified.get(key)).toBe(String(value));
});
});
});
describe('PATCH requests', () => {
it('encodes key,value pairs from postPayload', async () => {
expect.assertions(3);
const postPayload = { key: 'value', anotherKey: 1237 };
await callApi({ url: mockPatchUrl, method: 'PATCH', postPayload });
const calls = fetchMock.calls(mockPatchUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
Object.entries(postPayload).forEach(([key, value]) => {
expect(body.get(key)).toBe(JSON.stringify(value));
});
});
// the reason for this is to omit strings like 'undefined' from making their way to the backend
it('omits key,value pairs from postPayload that have undefined values (PATCH)', async () => {
expect.assertions(3);
const postPayload = { key: 'value', noValue: undefined };
await callApi({ url: mockPatchUrl, method: 'PATCH', postPayload });
const calls = fetchMock.calls(mockPatchUrl);
expect(calls).toHaveLength(1);
const fetchParams = calls[0][1];
const body = fetchParams.body as FormData;
expect(body.get('key')).toBe(JSON.stringify(postPayload.key));
expect(body.get('noValue')).toBeNull();
});
it('respects the stringify flag in PATCH requests', async () => {
const postPayload = {
string: 'value',
number: 1237,
array: [1, 2, 3],
object: { a: 'a', 1: 1 },
null: null,
emptyString: '',
};
expect.assertions(1 + 2 * Object.keys(postPayload).length);
await Promise.all([
callApi({ url: mockPatchUrl, method: 'PATCH', postPayload }),
callApi({ url: mockPatchUrl, method: 'PATCH', postPayload, stringify: false }),
]);
const calls = fetchMock.calls(mockPatchUrl);
expect(calls).toHaveLength(2);
const stringified = calls[0][1].body as FormData;
const unstringified = calls[1][1].body as FormData;
Object.entries(postPayload).forEach(([key, value]) => {
expect(stringified.get(key)).toBe(JSON.stringify(value));
expect(unstringified.get(key)).toBe(String(value));
});
});
});
describe('caching', () => {
const origLocation = self.location;
beforeAll(() => {
Object.defineProperty(self, 'location', { value: {} });
});
afterAll(() => {
Object.defineProperty(self, 'location', { value: origLocation });
});
beforeEach(() => {
self.location.protocol = 'https:';
return caches.delete(constants.CACHE_KEY);
});
it('caches requests with ETags', async () => {
expect.assertions(2);
await callApi({ url: mockCacheUrl, method: 'GET' });
const calls = fetchMock.calls(mockCacheUrl);
expect(calls).toHaveLength(1);
const supersetCache = await caches.open(constants.CACHE_KEY);
const cachedResponse = await supersetCache.match(mockCacheUrl);
expect(cachedResponse).toBeDefined();
});
it('will not use cache when running off an insecure connection', async () => {
expect.assertions(2);
self.location.protocol = 'http:';
await callApi({ url: mockCacheUrl, method: 'GET' });
const calls = fetchMock.calls(mockCacheUrl);
expect(calls).toHaveLength(1);
const supersetCache = await caches.open(constants.CACHE_KEY);
const cachedResponse = await supersetCache.match(mockCacheUrl);
expect(cachedResponse).toBeUndefined();
});
it('works when the Cache API is disabled', async () => {
expect.assertions(5);
// eslint-disable-next-line no-import-assign
Object.defineProperty(constants, 'CACHE_AVAILABLE', { value: false });
const firstResponse = await callApi({ url: mockCacheUrl, method: 'GET' });
const calls = fetchMock.calls(mockCacheUrl);
expect(calls).toHaveLength(1);
const firstBody = await firstResponse.text();
expect(firstBody).toEqual('BODY');
const secondResponse = await callApi({ url: mockCacheUrl, method: 'GET' });
const fetchParams = calls[1][1];
expect(calls).toHaveLength(2);
// second call should not have If-None-Match header
expect(fetchParams.headers).toBeUndefined();
const secondBody = await secondResponse.text();
expect(secondBody).toEqual('BODY');
// eslint-disable-next-line no-import-assign
Object.defineProperty(constants, 'CACHE_AVAILABLE', { value: true });
});
it('sends known ETags in the If-None-Match header', async () => {
expect.assertions(3);
// first call sets the cache
await callApi({ url: mockCacheUrl, method: 'GET' });
const calls = fetchMock.calls(mockCacheUrl);
expect(calls).toHaveLength(1);
// second call sends the Etag in the If-None-Match header
await callApi({ url: mockCacheUrl, method: 'GET' });
const fetchParams = calls[1][1];
const headers = { 'If-None-Match': 'etag' };
expect(calls).toHaveLength(2);
expect(fetchParams.headers).toEqual(
expect.objectContaining(headers) as typeof fetchParams.headers,
);
});
it('reuses cached responses on 304 status', async () => {
expect.assertions(3);
// first call sets the cache
await callApi({ url: mockCacheUrl, method: 'GET' });
const calls = fetchMock.calls(mockCacheUrl);
expect(calls).toHaveLength(1);
// second call reuses the cached payload on a 304
const mockCachedPayload = { status: 304 };
fetchMock.get(mockCacheUrl, mockCachedPayload, { overwriteRoutes: true });
const secondResponse = await callApi({ url: mockCacheUrl, method: 'GET' });
expect(calls).toHaveLength(2);
const secondBody = await secondResponse.text();
expect(secondBody).toEqual('BODY');
});
it('throws error when cache fails on 304', async () => {
expect.assertions(2);
// this should never happen, since a 304 is only returned if we have
// the cached response and sent the If-None-Match header
const mockUncachedUrl = '/mock/uncached/url';
const mockCachedPayload = { status: 304 };
fetchMock.get(mockUncachedUrl, mockCachedPayload);
try {
await callApi({ url: mockUncachedUrl, method: 'GET' });
} catch (error) {
const calls = fetchMock.calls(mockUncachedUrl);
expect(calls).toHaveLength(1);
expect((error as { message: string }).message).toEqual(
'Received 304 but no content is cached!',
);
}
});
it('returns original response if no Etag', async () => {
expect.assertions(3);
const url = mockGetUrl;
const response = await callApi({ url, method: 'GET' });
const calls = fetchMock.calls(url);
expect(calls).toHaveLength(1);
expect(response.status).toEqual(200);
const body = await response.json();
expect(body as typeof mockGetPayload).toEqual(mockGetPayload);
});
it('returns original response if status not 304 or 200', async () => {
expect.assertions(2);
const url = mockNotFound;
const response = await callApi({ url, method: 'GET' });
const calls = fetchMock.calls(url);
expect(calls).toHaveLength(1);
expect(response.status).toEqual(404);
});
});
it('rejects after retrying thrice if the request throws', async () => {
expect.assertions(3);
try {
await callApi({
fetchRetryOptions: DEFAULT_FETCH_RETRY_OPTIONS,
url: mockErrorUrl,
method: 'GET',
});
} catch (error) {
const err = error as { status: number; statusText: string };
expect(fetchMock.calls(mockErrorUrl)).toHaveLength(4);
expect(err.status).toBe(mockErrorPayload.status);
expect(err.statusText).toBe(mockErrorPayload.statusText);
}
});
it('rejects without retries if the config is set to 0 retries', async () => {
expect.assertions(3);
try {
await callApi({
fetchRetryOptions: { retries: 0 },
url: mockErrorUrl,
method: 'GET',
});
} catch (error) {
const err = error as { status: number; statusText: string };
expect(fetchMock.calls(mockErrorUrl)).toHaveLength(1);
expect(err.status).toBe(mockErrorPayload.status);
expect(err.statusText).toBe(mockErrorPayload.statusText);
}
});
it('rejects after retrying thrice if the request returns a 503', async () => {
expect.assertions(2);
const url = mock503;
const response = await callApi({
fetchRetryOptions: DEFAULT_FETCH_RETRY_OPTIONS,
url,
method: 'GET',
});
const calls = fetchMock.calls(url);
expect(calls).toHaveLength(4);
expect(response.status).toEqual(503);
});
it('invalid json for postPayload should thrown error', async () => {
expect.assertions(2);
try {
await callApi({
url: mockPostUrl,
method: 'POST',
postPayload: 'haha',
});
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toEqual('Invalid payload:\n\nhaha');
}
});
it('should accept search params object', async () => {
expect.assertions(3);
window.location.href = 'http://localhost';
fetchMock.get(`glob:*/get-search*`, { yes: 'ok' });
const response = await callApi({
url: '/get-search',
searchParams: {
abc: 1,
},
method: 'GET',
});
const result = await response.json();
expect(response.status).toEqual(200);
expect(result).toEqual({ yes: 'ok' });
expect(fetchMock.lastUrl()).toEqual(`http://localhost/get-search?abc=1`);
});
it('should accept URLSearchParams', async () => {
expect.assertions(2);
window.location.href = 'http://localhost';
fetchMock.post(`glob:*/post-search*`, { yes: 'ok' });
await callApi({
url: '/post-search',
searchParams: new URLSearchParams({
abc: '1',
}),
method: 'POST',
jsonPayload: { request: 'ok' },
});
expect(fetchMock.lastUrl()).toEqual(`http://localhost/post-search?abc=1`);
expect(fetchMock.lastOptions()).toEqual(
expect.objectContaining({
body: JSON.stringify({ request: 'ok' }),
}),
);
});
it('should throw when both payloads provided', async () => {
expect.assertions(1);
fetchMock.post('/post-both-payload', {});
try {
await callApi({
url: '/post-both-payload',
method: 'POST',
postPayload: { a: 1 },
jsonPayload: '{}',
});
} catch (error) {
expect((error as Error).message).toContain('provide only one of jsonPayload or postPayload');
}
});
it('should accept FormData as postPayload', async () => {
expect.assertions(1);
fetchMock.post('/post-formdata', {});
const payload = new FormData();
await callApi({
url: '/post-formdata',
method: 'POST',
postPayload: payload,
});
expect(fetchMock.lastOptions().body).toBe(payload);
});
it('should ignore "null" postPayload string', async () => {
expect.assertions(1);
fetchMock.post('/post-null-postpayload', {});
await callApi({
url: '/post-formdata',
method: 'POST',
postPayload: 'null',
});
expect(fetchMock.lastOptions().body).toBeUndefined();
});
});