-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindexSpec.js
More file actions
415 lines (358 loc) · 11.6 KB
/
Copy pathindexSpec.js
File metadata and controls
415 lines (358 loc) · 11.6 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
import { createMerkurWidget } from '@merkur/core';
import {
httpCachePlugin,
cacheInTransformer,
cacheOutTransformer,
internalCacheTransformer,
getCacheKey,
} from '../index';
import CacheEntry from '../CacheEntry';
import { componentPlugin } from '@merkur/plugin-component';
import {
httpClientPlugin,
setDefaultConfig,
getDefaultTransformers,
} from '@merkur/plugin-http-client';
describe('createWidget method with http client plugin', () => {
let widget = null;
let Response = null;
let cacheMock = null;
beforeEach(async () => {
widget = await createMerkurWidget({
$plugins: [componentPlugin, httpClientPlugin, httpCachePlugin],
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',
},
],
});
setDefaultConfig(widget, {
baseUrl: 'http://localhost:4444',
transformers: [
...getDefaultTransformers(),
cacheInTransformer(widget),
cacheOutTransformer(widget),
],
useCache: true,
});
cacheMock = {};
widget.$dependencies.fetch = jest.fn(() => Promise.resolve(Response));
widget.$in.httpClient.cache = {
get: jest.fn((key) => cacheMock[key]),
set: jest.fn((key, value) => (cacheMock[key] = value)),
};
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": [MockFunction],
},
"$external": {},
"$in": {
"component": {
"isHydrated": false,
"isMounted": false,
"lifeCycle": {
"bootstrap": undefined,
"info": undefined,
"load": undefined,
"mount": undefined,
"teardown": undefined,
"unmount": undefined,
"update": undefined,
},
"loadingPromise": null,
"resolvedViews": Map {},
"suspendedTasks": [],
},
"httpClient": {
"cache": {
"get": [MockFunction],
"set": [MockFunction],
},
"defaultConfig": {
"baseUrl": "http://localhost:4444",
"headers": {},
"method": "GET",
"query": {},
"timeout": 15000,
"transferServerCache": false,
"transformers": [
{
"transformRequest": [Function],
},
{
"transformRequest": [Function],
"transformResponse": [Function],
},
{
"transformRequest": [Function],
},
{
"transformRequest": [Function],
"transformResponse": [Function],
},
{
"transformResponse": [Function],
},
{
"transformRequest": [Function],
},
],
"ttl": 60000,
"useCache": true,
},
"pendingRequests": Map {},
},
},
"$plugins": [
{
"create": [Function],
"setup": [Function],
},
{
"create": [Function],
"setup": [Function],
},
{
"create": [Function],
"setup": [Function],
},
],
"assets": [
{
"source": "http://www.example.com/static/1.0.0/widget.js",
"type": "script",
},
],
"bootstrap": [Function],
"containerSelector": null,
"create": [Function],
"http": {
"request": [Function],
},
"httpCache": {
"deserialize": [Function],
"get": [Function],
"serialize": [Function],
},
"info": [Function],
"load": [Function],
"mount": [Function],
"name": "my-widget",
"props": {
"containerSelector": ".container",
"param": 1,
},
"setProps": [Function],
"setState": [Function],
"setup": [Function],
"slot": {},
"state": {},
"teardown": [Function],
"unmount": [Function],
"update": [Function],
"version": "1.0.0",
}
`);
});
it('should store response in cache', async () => {
const { request } = await widget.http.request({ path: '/path/to/url' });
const cacheKey = getCacheKey(request);
expect(widget.$in.httpClient.cache.set).toHaveBeenCalledWith(
cacheKey,
expect.any(CacheEntry),
);
expect(cacheMock[cacheKey]).toBeInstanceOf(CacheEntry);
});
it('should use response from cache', async () => {
const { request } = await widget.http.request({ path: '/path/to/url' });
const cacheKey = getCacheKey(request);
expect(widget.$in.httpClient.cache.set).toHaveBeenCalled();
const { response } = await widget.http.request({ path: '/path/to/url' });
expect(widget.$in.httpClient.cache.get).toHaveBeenCalledWith(cacheKey);
expect(response.cached).toBeTruthy();
});
it('should not read response from cache when revalidating', async () => {
const { request } = await widget.http.request({
path: '/path/to/url',
revalidateCache: true,
});
const cacheKey = getCacheKey(request);
expect(widget.$in.httpClient.cache.get).not.toHaveBeenCalled();
expect(widget.$in.httpClient.cache.set).toHaveBeenCalledWith(
cacheKey,
expect.any(CacheEntry),
);
expect(cacheMock[cacheKey]).toBeInstanceOf(CacheEntry);
});
it('should keep same cached value when mutating response object', async () => {
const { request } = await widget.http.request({ path: '/path/to/url' });
const cacheKey = getCacheKey(request);
const { response } = await widget.http.request({ path: '/path/to/url' });
response.body = { data: 'change' };
expect(cacheMock[cacheKey]._value.body).toEqual({ message: 'text' });
});
});
describe('internalCacheTransformer', () => {
let widget = null;
let fetchMock = null;
const makeResponse = (body = { message: 'text' }) => ({
json() {
return Promise.resolve(body);
},
ok: true,
headers: {
get() {
return 'application/json';
},
},
status: 200,
});
beforeEach(async () => {
widget = await createMerkurWidget({
$plugins: [componentPlugin, httpClientPlugin, httpCachePlugin],
name: 'my-widget',
version: '1.0.0',
props: {},
assets: [],
});
fetchMock = jest.fn(() => Promise.resolve(makeResponse()));
widget.$dependencies.fetch = fetchMock;
setDefaultConfig(widget, {
baseUrl: 'http://localhost:4444',
transformers: [
...getDefaultTransformers(),
cacheOutTransformer(widget),
internalCacheTransformer(widget),
cacheInTransformer(widget),
],
useCache: true,
});
});
it('should deduplicate concurrent requests – fetch called only once', async () => {
const [result1, result2] = await Promise.all([
widget.http.request({ path: '/api/data' }),
widget.http.request({ path: '/api/data' }),
]);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(result1.response.body).toEqual({ message: 'text' });
expect(result2.response.body).toEqual({ message: 'text' });
expect(result2.response.cached).toBe(true);
});
it('should clean up pendingRequests after successful request', async () => {
await widget.http.request({ path: '/api/data' });
expect(widget.$in.httpClient.pendingRequests.size).toBe(0);
});
it('should propagate error to all waiting requests', async () => {
const networkError = new Error('Network failure');
fetchMock.mockRejectedValueOnce(networkError);
const [p1, p2] = [
widget.http.request({ path: '/api/fail' }),
widget.http.request({ path: '/api/fail' }),
];
await expect(p1).rejects.toThrow('Network failure');
await expect(p2).rejects.toThrow('Network failure');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('should clean up pendingRequests after failed request', async () => {
fetchMock.mockRejectedValueOnce(new Error('fail'));
await widget.http.request({ path: '/api/fail' }).catch(() => {});
expect(widget.$in.httpClient.pendingRequests.size).toBe(0);
});
it('should bypass internalCache when revalidateCache is true', async () => {
// First request – populates resolved cache
await widget.http.request({ path: '/api/data' });
fetchMock
.mockResolvedValueOnce(makeResponse({ message: 'fresh-1' }))
.mockResolvedValueOnce(makeResponse({ message: 'fresh-2' }));
// Both revalidate requests must bypass internal cache and hit network independently
const [r1, r2] = await Promise.all([
widget.http.request({ path: '/api/data', revalidateCache: true }),
widget.http.request({ path: '/api/data', revalidateCache: true }),
]);
expect(fetchMock).toHaveBeenCalledTimes(3); // 1 initial + 2 revalidate
expect(r1.response.body).toEqual({ message: 'fresh-1' });
expect(r2.response.body).toEqual({ message: 'fresh-2' });
});
it('should not mark first (pending) request response as cached', async () => {
const [result1] = await Promise.all([
widget.http.request({ path: '/api/data' }),
widget.http.request({ path: '/api/data' }),
]);
expect(result1.response.cached).toBeUndefined();
});
describe('transformError', () => {
it('should reject waiting requests via transformError when first request fails', async () => {
const networkError = new Error('Network failure');
fetchMock.mockRejectedValueOnce(networkError);
const p1 = widget.http.request({ path: '/api/data' });
const p2 = widget.http.request({ path: '/api/data' });
await expect(p1).rejects.toThrow('Network failure');
await expect(p2).rejects.toThrow('Network failure');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('should clean up pendingRequests via transformError after network error', async () => {
fetchMock.mockRejectedValueOnce(new Error('fail'));
await widget.http.request({ path: '/api/data' }).catch(() => {});
expect(widget.$in.httpClient.pendingRequests.size).toBe(0);
});
it('should not call transformError when response comes from resolved cache', async () => {
// populate cache
await widget.http.request({ path: '/api/data' });
const errorTransformerSpy = jest.fn();
setDefaultConfig(widget, {
transformers: [
...getDefaultTransformers(),
cacheOutTransformer(widget),
internalCacheTransformer(widget),
cacheInTransformer(widget),
{ transformError: errorTransformerSpy },
],
});
fetchMock.mockRejectedValueOnce(new Error('never'));
// should be served from cache, fetch never called, transformError never called
const { response } = await widget.http.request({ path: '/api/data' });
expect(response.cached).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(1); // only the initial populate call
expect(errorTransformerSpy).not.toHaveBeenCalled();
});
it('should enrich thrown error with cause, request and response on network failure', async () => {
fetchMock.mockRejectedValueOnce(new Error('Network failure'));
const thrownError = await widget.http
.request({ path: '/api/data' })
.catch((e) => e);
expect(thrownError.cause).toEqual({
request: expect.objectContaining({
url: 'http://localhost:4444/api/data',
}),
response: null,
});
expect(thrownError.request).toEqual(
expect.objectContaining({ url: 'http://localhost:4444/api/data' }),
);
expect(thrownError.response).toBeNull();
});
});
});