-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindexSpec.js
More file actions
570 lines (492 loc) · 15.4 KB
/
Copy pathindexSpec.js
File metadata and controls
570 lines (492 loc) · 15.4 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
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
567
568
569
570
import { createMerkurWidget } from '@merkur/core';
import {
httpClientPlugin,
setDefaultConfig,
getDefaultTransformers,
transformHeaders,
} from '../index';
describe('createWidget method with http client plugin', () => {
let widget = null;
let Response = null;
beforeEach(async () => {
widget = await createMerkurWidget({
$plugins: [httpClientPlugin],
name: 'my-widget',
version: '1.0.0',
props: {
param: 1,
containerSelector: '.container',
},
assets: [
{
type: 'script',
source: 'http://www.example.com/static/1.0.0/widget.js',
},
],
});
function transformInCache(widget) {
widget.$in.httpClient.cache = {};
return {
async transformResponse(widget, request, response) {
if (request.cache) {
widget.$in.httpClient.cache[request.url] = response;
}
return [request, response];
},
};
}
function transformOutCache(widget) {
widget.$in.httpClient.cache = {};
return {
async transformRequest(widget, request, response) {
if (!widget.$in.httpClient.cache[request.url] || !request.cache) {
return [request, response];
}
return [request, widget.$in.httpClient.cache[request.url]];
},
};
}
setDefaultConfig(widget, {
baseUrl: 'http://localhost:4444',
transformers: [
transformInCache(widget),
...getDefaultTransformers(),
transformOutCache(widget),
],
});
Response = {
json() {
return Promise.resolve({ message: 'text' });
},
ok: true,
headers: {
get() {
return 'application/json';
},
},
status: 200,
};
});
it('should create empty widget', async () => {
expect(widget).toMatchInlineSnapshot(`
{
"$dependencies": {
"AbortController": [Function],
"fetch": [Function],
},
"$external": {},
"$in": {
"httpClient": {
"cache": {},
"defaultConfig": {
"baseUrl": "http://localhost:4444",
"headers": {},
"method": "GET",
"query": {},
"timeout": 15000,
"transformers": [
{
"transformResponse": [Function],
},
{
"transformRequest": [Function],
},
{
"transformRequest": [Function],
"transformResponse": [Function],
},
{
"transformRequest": [Function],
},
{
"transformRequest": [Function],
"transformResponse": [Function],
},
{
"transformRequest": [Function],
},
],
},
},
},
"$plugins": [
{
"create": [Function],
"setup": [Function],
},
],
"create": [Function],
"http": {
"request": [Function],
},
"name": "my-widget",
"setup": [Function],
"version": "1.0.0",
}
`);
});
describe('API request', () => {
beforeEach(() => {
widget.$dependencies.fetch = jest.fn(() => Promise.resolve(Response));
});
it('should generate absolute url', async () => {
const { request } = await widget.http.request({
path: '/path/to/url',
});
expect(request.url).toMatchInlineSnapshot(
`"http://localhost:4444/path/to/url"`,
);
});
it('should always generate valid absolute url', async () => {
let requests = [
{
baseUrl: 'http://base.com/',
path: '/route/id',
},
{
baseUrl: 'http://base.com',
path: '/route/id',
},
{
baseUrl: 'http://base.com',
path: 'route/id',
},
{
baseUrl: 'http://base.com/',
path: 'route/id',
},
];
await requests.forEach(async (request) => {
const { request: newRequest } = await widget.http.request({
baseUrl: request.baseUrl,
path: request.path,
});
expect(newRequest.url).toEqual('http://base.com/route/id');
});
});
it('should generate absolute url with query', async () => {
const { request } = await widget.http.request({
path: '/path?c=d',
});
expect(request.url).toMatchInlineSnapshot(
`"http://localhost:4444/path?c=d"`,
);
});
it('should generate new query string', async () => {
const { request } = await widget.http.request({
path: '/path',
query: { a: 'b' },
});
expect(request.url).toMatchInlineSnapshot(
`"http://localhost:4444/path?a=b"`,
);
});
it('should generate add query string to existing one', async () => {
const { request } = await widget.http.request({
path: '/path?c=d',
query: { a: 'b' },
});
expect(request.url).toMatchInlineSnapshot(
`"http://localhost:4444/path?c=d&a=b"`,
);
});
it('should send body', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path?c=d',
body: { a: 'b' },
headers: {
'Content-Type': 'application/json',
},
});
expect(request.body).toMatchInlineSnapshot(`"{"a":"b"}"`);
});
it('should send body with lowercase header content-type', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path?c=d',
body: { a: 'b' },
headers: {
'content-type': 'application/json',
},
});
expect(request.body).toMatchInlineSnapshot(`"{"a":"b"}"`);
});
it('should set default Content-Type application/json for POST with body', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: { a: 'b' },
headers: {},
});
expect(request.headers.get('Content-Type')).toBe('application/json');
expect(request.body).toMatchInlineSnapshot(`"{"a":"b"}"`);
});
it('should not override explicit Content-Type when body is present', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: 'raw text',
headers: {
'Content-Type': 'text/plain',
},
});
expect(request.headers.get('Content-Type')).toBe('text/plain');
expect(request.body).toBe('raw text');
});
it('should not set default Content-Type for GET with body', async () => {
const { request } = await widget.http.request({
method: 'GET',
path: '/path',
body: { a: 'b' },
headers: {},
});
expect(request.headers.get('Content-Type')).toBeNull();
});
it('should set default Content-Type when headers is a Headers instance', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: { a: 'b' },
headers: new Headers(),
});
expect(request.headers.get('Content-Type')).toBe('application/json');
expect(request.body).toMatchInlineSnapshot(`"{"a":"b"}"`);
});
it('should serialize body when headers is a Headers instance with Content-Type', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: { a: 'b' },
headers: new Headers({ 'Content-Type': 'application/json' }),
});
expect(request.headers.get('content-type')).toBe('application/json');
expect(request.body).toMatchInlineSnapshot(`"{"a":"b"}"`);
});
it('should not override Content-Type when headers is a Headers instance with custom type', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: 'raw',
headers: new Headers({ 'Content-Type': 'text/plain' }),
});
expect(request.headers.get('content-type')).toBe('text/plain');
expect(request.body).toBe('raw');
});
it('should preserve existing entries when headers is a Headers instance', async () => {
const { request } = await widget.http.request({
method: 'POST',
path: '/path',
body: { a: 'b' },
headers: new Headers({
Authorization: 'Bearer token',
'X-Request-ID': '42',
}),
});
expect(request.headers.get('Authorization')).toBe('Bearer token');
expect(request.headers.get('X-Request-ID')).toBe('42');
expect(request.headers.get('Content-Type')).toBe('application/json');
});
it('should timeout request which exceed predefined timeout limit', async () => {
widget.$dependencies.fetch = jest.fn((url, request) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
request.signal.aborted ? reject(new Error('Timeout')) : resolve();
}, 10);
});
});
try {
await widget.http.request({
path: '/path',
timeout: 5,
});
} catch (error) {
expect(error.message).toEqual('Timeout');
expect(widget.$dependencies.fetch).toHaveBeenCalled();
}
});
});
describe('API response', () => {
beforeEach(() => {
widget.$dependencies.fetch = jest.fn(() => Promise.resolve(Response));
});
it('should add parsed body to response', async () => {
const { response } = await widget.http.request({
path: '/path',
});
expect(response.body).toMatchInlineSnapshot(`
{
"message": "text",
}
`);
});
it('should intercept request and return response from request transformer', async () => {
const { response } = await widget.http.request({
path: '/path',
cache: true,
});
const { response: cachedResponse } = await widget.http.request({
path: '/path',
cache: true,
});
expect(response).toEqual(cachedResponse);
expect(widget.$dependencies.fetch.mock.calls.length).toEqual(1);
});
it('should reject promise for status code greater than 299', async () => {
widget.$dependencies.fetch = jest.fn(() =>
Promise.resolve({ ...Response, ...{ ok: false } }),
);
try {
await widget.http.request({
path: '/path',
cache: true,
});
} catch ({ response, request }) {
expect(request.url).toMatchInlineSnapshot(
`"http://localhost:4444/path"`,
);
expect(response).toMatchInlineSnapshot(`
{
"body": {
"message": "text",
},
"headers": {
"get": [Function],
},
"ok": false,
"redirected": undefined,
"status": 200,
"statusText": undefined,
"trailers": undefined,
"type": undefined,
"url": undefined,
"useFinalURL": undefined,
}
`);
}
});
});
describe('transformError', () => {
let errorTransformerSpy;
beforeEach(() => {
errorTransformerSpy = jest.fn((widget, error, request) => [
error,
request,
]);
setDefaultConfig(widget, {
transformers: [
...getDefaultTransformers(),
{
transformError: errorTransformerSpy,
},
],
});
widget.$dependencies.fetch = jest.fn(() => Promise.resolve(Response));
});
it('should call transformError on fetch network error', async () => {
const networkError = new Error('Network failure');
widget.$dependencies.fetch = jest.fn(() => Promise.reject(networkError));
await expect(widget.http.request({ path: '/path' })).rejects.toThrow(
'Network failure',
);
expect(errorTransformerSpy).toHaveBeenCalledWith(
widget,
networkError,
expect.objectContaining({ url: 'http://localhost:4444/path' }),
);
});
it('should call transformError with the fully transformed request object', async () => {
const networkError = new Error('fail');
widget.$dependencies.fetch = jest.fn(() => Promise.reject(networkError));
await widget.http.request({ path: '/path' }).catch(() => {});
const [, , requestArg] = errorTransformerSpy.mock.calls[0];
expect(requestArg.url).toBe('http://localhost:4444/path');
expect(requestArg.method).toBe('GET');
});
it('should still throw after transformError runs', async () => {
widget.$dependencies.fetch = jest.fn(() =>
Promise.reject(new Error('boom')),
);
await expect(widget.http.request({ path: '/path' })).rejects.toThrow(
'boom',
);
});
it('should enrich thrown error with cause, request and response', async () => {
const networkError = new Error('Network failure');
widget.$dependencies.fetch = jest.fn(() => Promise.reject(networkError));
const thrownError = await widget.http
.request({ path: '/path' })
.catch((e) => e);
expect(thrownError.cause).toEqual({
request: expect.objectContaining({ url: 'http://localhost:4444/path' }),
response: null,
});
expect(thrownError.request).toEqual(
expect.objectContaining({ url: 'http://localhost:4444/path' }),
);
expect(thrownError.response).toBeNull();
});
it('should not call transformError on successful fetch', async () => {
await widget.http.request({ path: '/path' });
expect(errorTransformerSpy).not.toHaveBeenCalled();
});
it('should not call transformError when response is already set by transformRequest', async () => {
setDefaultConfig(widget, {
transformers: [
{
transformRequest(widget, request) {
return [request, Response];
},
transformError: errorTransformerSpy,
},
],
});
widget.$dependencies.fetch = jest.fn(() =>
Promise.reject(new Error('never')),
);
await widget.http.request({ path: '/path' });
expect(errorTransformerSpy).not.toHaveBeenCalled();
expect(widget.$dependencies.fetch).not.toHaveBeenCalled();
});
});
});
describe('transformHeaders', () => {
const transformer = transformHeaders();
it('should normalize a plain object to a Headers instance', async () => {
const [result] = await transformer.transformRequest(
null,
{ headers: { Authorization: 'Bearer token' } },
null,
);
expect(result.headers).toBeInstanceOf(Headers);
expect(result.headers.get('Authorization')).toBe('Bearer token');
});
it('should normalize a Headers instance to a new Headers instance', async () => {
const input = new Headers({ 'X-Custom': 'value' });
const [result] = await transformer.transformRequest(
null,
{ headers: input },
null,
);
expect(result.headers).toBeInstanceOf(Headers);
expect(result.headers.get('X-Custom')).toBe('value');
});
it('should normalize null headers to an empty Headers instance', async () => {
const [result] = await transformer.transformRequest(
null,
{ headers: null },
null,
);
expect(result.headers).toBeInstanceOf(Headers);
expect([...result.headers.entries()]).toHaveLength(0);
});
it('should preserve the response unchanged', async () => {
const response = { ok: true };
const [, resultResponse] = await transformer.transformRequest(
null,
{ headers: {} },
response,
);
expect(resultResponse).toBe(response);
});
});