-
-
Notifications
You must be signed in to change notification settings - Fork 736
/
image_request.test.ts
408 lines (311 loc) · 16 KB
/
image_request.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
import {config} from './config';
import {webpSupported} from './webp_supported';
import {sleep, stubAjaxGetImage} from './test/util';
import {fakeServer, type FakeServer} from 'nise';
import {ImageRequest} from './image_request';
import {isAbortError} from './abort_error';
import * as ajax from './ajax';
describe('ImageRequest', () => {
let server: FakeServer;
beforeEach(() => {
global.fetch = null;
server = fakeServer.create();
ImageRequest.resetRequestQueue();
stubAjaxGetImage(undefined);
});
afterEach(() => {
server.restore();
});
test('getImage respects maxParallelImageRequests', async () => {
server.respondWith(request => request.respond(200, {'Content-Type': 'image/png'}, ''));
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
const promises: Promise<any>[] = [];
for (let i = 0; i < maxRequests + 5; i++) {
promises.push(ImageRequest.getImage({url: ''}, new AbortController()));
}
expect(server.requests).toHaveLength(maxRequests);
server.requests[0].respond(200);
await promises[0];
expect(server.requests).toHaveLength(maxRequests + 1);
server.requests[1].respond(200);
await promises[1];
expect(server.requests).toHaveLength(maxRequests + 2);
});
test('getImage respects maxParallelImageRequests and continues to respond even when server returns 404', async () => {
server.respondWith(request => request.respond(404));
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
for (let i = 0; i < maxRequests + 5; i++) {
ImageRequest.getImage({url: ''}, new AbortController()).catch(() => {});
}
expect(server.requests).toHaveLength(maxRequests);
server.respond();
await sleep(0);
expect(server.requests).toHaveLength(maxRequests + 5);
});
test('Cancel: getImage cancelling frees up request for maxParallelImageRequests', async () => {
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
for (let i = 0; i < maxRequests + 1; i++) {
const abortController = new AbortController();
ImageRequest.getImage({url: ''}, abortController).catch((e) => expect(isAbortError(e)).toBeTruthy());
abortController.abort();
await sleep(0);
}
expect(server.requests).toHaveLength(maxRequests + 1);
});
test('Cancel: getImage requests that were once queued are still abortable', async () => {
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
const abortControllers: AbortController[] = [];
for (let i = 0; i < maxRequests; i++) {
const abortController = new AbortController();
abortControllers.push(abortController);
ImageRequest.getImage({url: ''}, abortController).catch(() => {});
}
// the limit of allowed requests is reached
expect(server.requests).toHaveLength(maxRequests);
const queuedURL = 'this-is-the-queued-request';
const abortController = new AbortController();
ImageRequest.getImage({url: queuedURL}, abortController).catch((e) => expect(isAbortError(e)).toBeTruthy());
// the new requests is queued because the limit is reached
expect(server.requests).toHaveLength(maxRequests);
// cancel the first request to let the queued request start
abortControllers[0].abort();
await sleep(0);
expect(server.requests).toHaveLength(maxRequests + 1);
// abort the previously queued request and confirm that it is aborted
const queuedRequest = server.requests[server.requests.length - 1];
expect(queuedRequest.url).toBe(queuedURL);
expect((queuedRequest as any).aborted).toBeUndefined();
abortController.abort();
expect((queuedRequest as any).aborted).toBe(true);
});
test('getImage sends accept/webp when supported', async () => {
server.respondWith((request) => {
expect(request.requestHeaders.accept.includes('image/webp')).toBeTruthy();
request.respond(200, {'Content-Type': 'image/webp'}, '');
});
// mock webp support
webpSupported.supported = true;
const promise = ImageRequest.getImage({url: ''}, new AbortController());
server.respond();
await expect(promise).resolves.toBeDefined();
});
test('getImage uses createImageBitmap when supported', async () => {
server.respondWith(request => request.respond(200, {'Content-Type': 'image/png',
'Cache-Control': 'cache',
'Expires': 'expires'}, ''));
stubAjaxGetImage(() => Promise.resolve(new ImageBitmap()));
const promise = ImageRequest.getImage({url: ''}, new AbortController());
server.respond();
const response = await promise;
expect(response.data).toBeInstanceOf(ImageBitmap);
expect(response.cacheControl).toBe('cache');
expect(response.expires).toBe('expires');
});
test('getImage using createImageBitmap throws exception', async () => {
server.respondWith(request => request.respond(200, {'Content-Type': 'image/png',
'Cache-Control': 'cache',
'Expires': 'expires'}, ''));
stubAjaxGetImage(() => Promise.reject(new Error('error')));
const promise = ImageRequest.getImage({url: ''}, new AbortController());
server.respond();
await expect(promise).rejects.toThrow();
});
test('getImage uses HTMLImageElement when createImageBitmap is not supported', async () => {
const makeRequestSky = jest.spyOn(ajax, 'makeRequest');
server.respondWith(request => request.respond(200, {'Content-Type': 'image/png',
'Cache-Control': 'cache',
'Expires': 'expires'}, ''));
const promise = ImageRequest.getImage({url: ''}, new AbortController());
server.respond();
expect(makeRequestSky).toHaveBeenCalledTimes(1);
makeRequestSky.mockClear();
const response = await promise;
expect(response.data).toBeInstanceOf(HTMLImageElement);
expect(response.cacheControl).toBe('cache');
expect(response.expires).toBe('expires');
});
test('getImage using HTMLImageElement with same-origin credentials', async () => {
const makeRequestSky = jest.spyOn(ajax, 'makeRequest');
const promise = ImageRequest.getImage({url: '', credentials: 'same-origin'}, new AbortController(), false);
expect(makeRequestSky).toHaveBeenCalledTimes(0);
makeRequestSky.mockClear();
const response = await promise;
expect(response.data).toBeInstanceOf(HTMLImageElement);
expect((response.data as HTMLImageElement).crossOrigin).toBe('anonymous');
});
test('getImage using HTMLImageElement with include credentials', async () => {
const makeRequestSky = jest.spyOn(ajax, 'makeRequest');
const promise = ImageRequest.getImage({url: '', credentials: 'include'}, new AbortController(), false);
expect(makeRequestSky).toHaveBeenCalledTimes(0);
makeRequestSky.mockClear();
const response = await promise;
expect(response.data).toBeInstanceOf(HTMLImageElement);
expect((response.data as HTMLImageElement).crossOrigin).toBe('use-credentials');
});
test('getImage using HTMLImageElement with accept header', async () => {
const makeRequestSky = jest.spyOn(ajax, 'makeRequest');
const promise = ImageRequest.getImage({url: '', credentials: 'include', headers: {accept: 'accept'}}, new AbortController(), false);
expect(makeRequestSky).toHaveBeenCalledTimes(0);
makeRequestSky.mockClear();
const response = await promise;
expect(response.data).toBeInstanceOf(HTMLImageElement);
expect((response.data as HTMLImageElement).crossOrigin).toBe('use-credentials');
});
test('getImage uses makeRequest when custom Headers are added', () => {
const makeRequestSky = jest.spyOn(ajax, 'makeRequest');
ImageRequest.getImage({url: '', credentials: 'include', headers: {custom: 'test', accept: 'image'}}, new AbortController(), false);
expect(makeRequestSky).toHaveBeenCalledTimes(1);
makeRequestSky.mockClear();
});
test('getImage request returned 404 response for fetch request', async () => {
server.respondWith(request => request.respond(404));
const promise = ImageRequest.getImage({url: ''}, new AbortController());
server.respond();
await expect(promise).rejects.toThrow('Not Found');
});
test('getImage request failed for HTTPImageRequest', async () => {
const promise = ImageRequest.getImage({url: 'error'}, new AbortController(), false);
await expect(promise).rejects.toThrow(/Could not load image.*/);
});
test('Cancel: getImage request cancelled for HTTPImageRequest', async () => {
let imageUrl;
const requestUrl = 'test';
// eslint-disable-next-line accessor-pairs
Object.defineProperty(global.Image.prototype, 'src', {
set(url: string) {
imageUrl = url;
}
});
const abortController = new AbortController();
ImageRequest.getImage({url: requestUrl}, abortController, false).catch(() => {});
expect(imageUrl).toBe(requestUrl);
expect(abortController.signal.aborted).toBeFalsy();
abortController.abort();
expect(abortController.signal.aborted).toBeTruthy();
expect(imageUrl).toBe('');
});
test('Cancel: getImage request cancelled', async () => {
server.respondWith(request => request.respond(200, {'Content-Type': 'image/png',
'Cache-Control': 'cache',
'Expires': 'expires'}, ''));
const abortController = new AbortController();
let response = false;
ImageRequest.getImage({url: ''}, abortController)
.then(() => { response = true; })
.catch(() => { response = true; });
abortController.abort();
server.respond();
expect(response).toBeFalsy();
});
test('Cancel: Cancellation of an image which has not yet been requested', async () => {
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
let callbackCounter = 0;
const promiseCallback = () => { callbackCounter++; };
const abortConstollers: {url: string; abortController: AbortController}[] = [];
for (let i = 0; i < maxRequests + 100; i++) {
const url = `${i}`;
const abortController = new AbortController();
abortConstollers.push({url, abortController});
ImageRequest.getImage({url}, abortController).then(promiseCallback).catch(() => {});
}
abortConstollers[0].abortController.abort();
await sleep(0);
// Queue should move forward and next request is made
expect(server.requests).toHaveLength(maxRequests + 1);
// Cancel request should not call callback
expect(callbackCounter).toBe(0);
// Cancel request which is not yet issued. It should not fire callback
const nextRequestInQueue = abortConstollers[server.requests.length];
const cancelledImageUrl = nextRequestInQueue.url;
nextRequestInQueue.abortController.abort();
// Queue should not move forward as cancelled image was sitting in queue
expect(server.requests).toHaveLength(maxRequests + 1);
expect(callbackCounter).toBe(0);
// On server response, next image queued should not be the cancelled image
server.requests[1].respond(200);
await sleep(0);
expect(callbackCounter).toBe(1);
expect(server.requests).toHaveLength(maxRequests + 2);
// Verify that the last request made skipped the cancelled image request
expect(server.requests[server.requests.length - 1].url).toBe((parseInt(cancelledImageUrl) + 1).toString());
});
test('throttling: one throttling client will result in throttle behavior for all', () => {
const maxRequestsPerFrame = config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME;
const callbackHandles = [];
// add one for each
callbackHandles.push(ImageRequest.addThrottleControl(() => false));
callbackHandles.push(ImageRequest.addThrottleControl(() => true));
let callbackCounter = 0;
const promiseCallback = () => { callbackCounter++; };
for (let i = 0; i < maxRequestsPerFrame + 1; i++) {
ImageRequest.getImage({url: ''}, new AbortController()).then(promiseCallback);
}
expect(server.requests).toHaveLength(maxRequestsPerFrame);
// all pending
expect(callbackCounter).toBe(0);
for (const handle of callbackHandles) {
ImageRequest.removeThrottleControl(handle);
}
});
test('throttling: image queue will process MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME if throttling control returns true', () => {
const maxRequestsPerFrame = config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME;
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
const controlId = ImageRequest.addThrottleControl(() => true);
let callbackCounter = 0;
const promiseCallback = () => { callbackCounter++; };
for (let i = 0; i < maxRequests; i++) {
ImageRequest.getImage({url: ''}, new AbortController()).then(promiseCallback);
}
// Should only fire request to a max allowed per frame
expect(server.requests).toHaveLength(maxRequestsPerFrame);
// all pending
expect(callbackCounter).toBe(0);
ImageRequest.removeThrottleControl(controlId);
});
test('throttling: image queue will process MAX_PARALLEL_IMAGE_REQUESTS if throttling control returns false', () => {
const maxRequests = config.MAX_PARALLEL_IMAGE_REQUESTS;
const controlId = ImageRequest.addThrottleControl(() => false);
let callbackCounter = 0;
const promiseCallback = () => { callbackCounter++; };
for (let i = 0; i < maxRequests + 100; i++) {
ImageRequest.getImage({url: ''}, new AbortController()).then(promiseCallback);
}
// all should be processed because throttle control is returning false
expect(server.requests).toHaveLength(maxRequests);
// all pending
expect(callbackCounter).toBe(0);
ImageRequest.removeThrottleControl(controlId);
});
test('throttling: removing throttling client will process all requests', async () => {
const requestParameter = {'Content-Type': 'image/png', url: ''};
const maxRequestsPerFrame = config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME;
// add 10, and one of them is throttling
const throttlingIndex = 5;
for (let i = 0; i < 10; i++) {
const throttlingClient: boolean = (i === throttlingIndex);
ImageRequest.addThrottleControl(() => throttlingClient);
}
// make 2 times + 1 more requests
const requestsMade = 2 * maxRequestsPerFrame + 1;
const completedMap: {[index: number]: boolean} = {};
for (let i = 0; i < requestsMade; i++) {
const promise = ImageRequest.getImage(requestParameter, new AbortController());
promise.catch(() => {});
promise.then(() => { completedMap[i] = true; });
}
// up to the config value
expect(server.requests).toHaveLength(maxRequestsPerFrame);
const itemIndexToComplete = 6;
server.requests[itemIndexToComplete].respond(200);
// unleash it by removing the throttling client
ImageRequest.removeThrottleControl(throttlingIndex);
await sleep(0);
expect(server.requests).toHaveLength(requestsMade);
// all pending
expect(Object.keys(completedMap)).toHaveLength(1);
// everything should still be pending except itemIndexToComplete
for (let i = 0; i < maxRequestsPerFrame + 1; i++) {
expect(completedMap[i]).toBe(i === itemIndexToComplete ? true : undefined);
}
});
});