/
fetch_spec.ts
509 lines (451 loc) Β· 17.6 KB
/
fetch_spec.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HttpEvent, HttpEventType, HttpRequest, HttpResponse} from '@angular/common/http';
import {TestBed} from '@angular/core/testing';
import {Observable, of, Subject} from 'rxjs';
import {catchError, retry, scan, skip, take, toArray} from 'rxjs/operators';
import {HttpDownloadProgressEvent, HttpErrorResponse, HttpHeaderResponse, HttpParams, HttpStatusCode} from '../public_api';
import {FetchBackend, FetchFactory} from '../src/fetch';
function trackEvents(obs: Observable<any>): Promise<any[]> {
return obs
.pipe(
// We don't want the promise to fail on HttpErrorResponse
catchError((e) => of(e)),
scan(
(acc, event) => {
acc.push(event);
return acc;
},
[] as any[]),
)
.toPromise();
}
const TEST_POST = new HttpRequest('POST', '/test', 'some body', {
responseType: 'text',
});
const TEST_POST_WITH_JSON_BODY = new HttpRequest('POST', '/test', {'some': 'body'}, {
responseType: 'text',
});
const XSSI_PREFIX = ')]}\'\n';
describe('FetchBackend', async () => {
let fetchMock: MockFetchFactory = null!;
let backend: FetchBackend = null!;
let fetchSpy: jasmine.Spy<typeof fetch>;
function callFetchAndFlush(req: HttpRequest<any>): void {
backend.handle(req).pipe(take(1)).subscribe();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: FetchFactory, useClass: MockFetchFactory},
FetchBackend,
]
});
fetchMock = TestBed.inject(FetchFactory) as MockFetchFactory;
fetchSpy = spyOn(fetchMock, 'fetch').and.callThrough();
backend = TestBed.inject(FetchBackend);
});
it('emits status immediately', () => {
let event!: HttpEvent<any>;
// subscribe is sync
backend.handle(TEST_POST).pipe(take(1)).subscribe((e) => event = e);
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
expect(event.type).toBe(HttpEventType.Sent);
});
it('should not call fetch without a subscribe', () => {
const handle = backend.handle(TEST_POST);
expect(fetchSpy).not.toHaveBeenCalled();
handle.subscribe();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
expect(fetchSpy).toHaveBeenCalled();
});
it('should be able to retry', ((done) => {
const handle = backend.handle(TEST_POST);
// Skipping both HttpSentEvent (from the 1st subscription + retry)
handle.pipe(retry(1), skip(2)).subscribe((response) => {
expect(response.type).toBe(HttpEventType.Response);
expect((response as HttpResponse<any>).body).toBe('some response');
done();
});
fetchMock.mockErrorEvent('Error 1');
fetchMock.resetFetchPromise();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
}));
it('sets method, url, and responseType correctly', () => {
callFetchAndFlush(TEST_POST);
expect(fetchMock.request.method).toBe('POST');
expect(fetchMock.request.url).toBe('/test');
});
it('use query params from request', () => {
const requestWithQuery = new HttpRequest('GET', '/test', 'some body', {
params: new HttpParams({fromObject: {query: 'foobar'}}),
responseType: 'text',
});
callFetchAndFlush(requestWithQuery);
expect(fetchMock.request.method).toBe('GET');
expect(fetchMock.request.url).toBe('/test?query=foobar');
});
it('sets outgoing body correctly', () => {
callFetchAndFlush(TEST_POST);
expect(fetchMock.request.body).toBe('some body');
});
it('sets outgoing body correctly when request payload is json', () => {
callFetchAndFlush(TEST_POST_WITH_JSON_BODY);
expect(fetchMock.request.body).toBe('{"some":"body"}');
});
it('sets outgoing headers, including default headers', () => {
const post = TEST_POST.clone({
setHeaders: {
'Test': 'Test header',
},
});
callFetchAndFlush(post);
expect(fetchMock.request.headers).toEqual({
'Test': 'Test header',
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'text/plain',
});
});
it('sets outgoing headers, including overriding defaults', () => {
const setHeaders = {
'Test': 'Test header',
'Accept': 'text/html',
'Content-Type': 'text/css',
};
callFetchAndFlush(TEST_POST.clone({setHeaders}));
expect(fetchMock.request.headers).toEqual(setHeaders);
});
it('passes withCredentials through', () => {
callFetchAndFlush(TEST_POST.clone({withCredentials: true}));
expect(fetchMock.request.credentials).toBe('include');
});
it('handles a text response', (async () => {
const promise = trackEvents(backend.handle(TEST_POST));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
const events = await promise;
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
expect(events[1] instanceof HttpResponse).toBeTruthy();
const res = events[1] as HttpResponse<string>;
expect(res.body).toBe('some response');
expect(res.status).toBe(HttpStatusCode.Ok);
expect(res.statusText).toBe('OK');
}));
it('handles a json response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body!.data).toBe('some data');
});
it('handles a blank json response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', '');
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body).toBeNull();
});
it('handles a json error response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(
HttpStatusCode.InternalServerError, 'Error', JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as any as HttpErrorResponse;
expect(res.error.data).toBe('some data');
});
it('handles a json error response with XSSI prefix', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(
HttpStatusCode.InternalServerError, 'Error',
XSSI_PREFIX + JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as any as HttpErrorResponse;
expect(res.error.data).toBe('some data');
});
it('handles a json string response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify('this is a string'));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<string>;
expect(res.body).toEqual('this is a string');
});
it('handles a json response with an XSSI prefix', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', XSSI_PREFIX + JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body!.data).toBe('some data');
});
it('handles a blob with a mime type', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'blob'})));
const type = 'aplication/pdf';
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', new Blob(), {'Content-Type': type});
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<Blob>;
expect(res.body?.type).toBe(type);
});
it('emits unsuccessful responses via the error path', done => {
backend.handle(TEST_POST).subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error).toBe('this is the error');
done();
}
});
fetchMock.mockFlush(HttpStatusCode.BadRequest, 'Bad Request', 'this is the error');
});
it('emits real errors via the error path', done => {
// Skipping the HttpEventType.Sent that is sent first
backend.handle(TEST_POST).pipe(skip(1)).subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error instanceof Error).toBeTrue();
expect(err.url).toBe('/test');
done();
}
});
fetchMock.mockErrorEvent(new Error('blah'));
});
it('emits an error when browser cancels a request', done => {
backend.handle(TEST_POST).subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error instanceof DOMException).toBeTruthy();
done();
}
});
fetchMock.mockAbortEvent();
});
describe('progress events', () => {
it('are emitted for download progress', done => {
backend.handle(TEST_POST.clone({reportProgress: true})).pipe(toArray()).subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const [progress1, progress2, response] = [
events[2] as HttpDownloadProgressEvent, events[3] as HttpDownloadProgressEvent,
events[5] as HttpResponse<string>
];
expect(progress1.partialText).toBe('down');
expect(progress1.loaded).toBe(4);
expect(progress1.total).toBe(10);
expect(progress2.partialText).toBe('download');
expect(progress2.loaded).toBe(8);
expect(progress2.total).toBe(10);
expect(response.body).toBe('downloaded');
done();
});
fetchMock.mockProgressEvent(4);
fetchMock.mockProgressEvent(8);
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'downloaded');
});
it('include ResponseHeader with headers and status', done => {
backend.handle(TEST_POST.clone({reportProgress: true})).pipe(toArray()).subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const partial = events[1] as HttpHeaderResponse;
expect(partial.type).toEqual(HttpEventType.ResponseHeader);
expect(partial.headers.get('Content-Type')).toEqual('text/plain');
expect(partial.headers.get('Test')).toEqual('Test header');
done();
});
fetchMock.response.headers = {'Test': 'Test header', 'Content-Type': 'text/plain'};
fetchMock.mockProgressEvent(200);
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done');
});
});
describe('gets response URL', async () => {
it('from the response URL', done => {
backend.handle(TEST_POST).pipe(toArray()).subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
fetchMock.response.url = '/response/url';
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
it('from X-Request-URL header if the response URL is not present', done => {
backend.handle(TEST_POST).pipe(toArray()).subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
fetchMock.response.headers = {'X-Request-URL': '/response/url'};
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
it('falls back on Request.url if neither are available', done => {
backend.handle(TEST_POST).pipe(toArray()).subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/test');
done();
});
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
});
describe('corrects for quirks', async () => {
it('by normalizing 0 status to 200 if a body is present', done => {
backend.handle(TEST_POST).pipe(toArray()).subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.status).toBe(HttpStatusCode.Ok);
done();
});
fetchMock.mockFlush(0, 'CORS 0 status', 'Test');
});
it('by leaving 0 status as 0 if a body is not present', done => {
backend.handle(TEST_POST).pipe(toArray()).subscribe({
error: (error: HttpErrorResponse) => {
expect(error.status).toBe(0);
done();
}
});
fetchMock.mockFlush(0, 'CORS 0 status');
});
});
});
export class MockFetchFactory extends FetchFactory {
public readonly response = new MockFetchResponse();
public readonly request = new MockFetchRequest();
private resolve!: Function;
private reject!: Function;
private clearWarningTimeout?: VoidFunction;
private promise = new Promise<Response>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
override fetch = (input: RequestInfo|URL, init?: RequestInit):
Promise<Response> => {
this.request.method = init?.method;
this.request.url = input;
this.request.body = init?.body;
this.request.headers = init?.headers;
this.request.credentials = init?.credentials;
if (init?.signal) {
init?.signal.addEventListener('abort', () => {
this.reject();
this.clearWarningTimeout?.();
});
}
// Fetch uses a Macrotask to keep the NgZone unstable during the fetch
// If the promise is not resolved/rejected the unit will succeed but the test suite will
// fail with a timeout
const timeoutId = setTimeout(() => {
console.error('********* You forgot to resolve/reject the promise ********* ');
this.reject();
}, 5000);
this.clearWarningTimeout = () => clearTimeout(timeoutId);
return this.promise;
}
mockFlush(
status: number, statusText: string, body?: string|Blob, headers?: Record<string, string>):
void {
this.clearWarningTimeout?.();
if (typeof body === 'string') {
this.response.setupBodyStream(body);
} else {
this.response.setBody(body);
}
const response = new Response(
this.response.stream,
{statusText, headers: {...this.response.headers, ...(headers ?? {})}});
// Have to be set outside the constructor because it might throw
// RangeError: init["status"] must be in the range of 200 to 599, inclusive
Object.defineProperty(response, 'status', {value: status});
if (this.response.url) {
// url is readonly
Object.defineProperty(response, 'url', {value: this.response.url});
}
this.resolve(response);
}
mockProgressEvent(loaded: number): void {
this.response.progress.push(loaded);
}
mockErrorEvent(error: any) {
this.reject(error);
}
mockAbortEvent() {
// When `abort()` is called, the fetch() promise rejects with an Error of type DOMException,
// with name AbortError. see
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
this.reject(new DOMException('', 'AbortError'));
}
resetFetchPromise() {
this.promise = new Promise<Response>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
class MockFetchRequest {
public url!: RequestInfo|URL;
public method?: string;
public body: any;
public credentials?: RequestCredentials;
public headers?: HeadersInit;
}
class MockFetchResponse {
public url?: string;
public headers: Record<string, string> = {};
public progress: number[] = [];
private sub$ = new Subject<any>();
public stream = new ReadableStream({
start: (controller) => {
this.sub$.subscribe({
next: (val) => {
controller.enqueue(new TextEncoder().encode(val));
},
complete: () => {
controller.close();
}
});
},
});
public setBody(body: any) {
this.sub$.next(body);
this.sub$.complete();
}
public setupBodyStream(body?: string) {
if (body && this.progress.length) {
this.headers['content-length'] = `${body.length}`;
let shift = 0;
this.progress.forEach((loaded) => {
this.sub$.next(body.substring(shift, loaded));
shift = loaded;
});
this.sub$.next(body.substring(shift, body.length));
} else {
this.sub$.next(body);
}
this.sub$.complete();
}
}