@@ -12,11 +12,14 @@ import {Observable, of, Subject} from 'rxjs';
12
12
import { catchError , retry , scan , skip , take , toArray } from 'rxjs/operators' ;
13
13
14
14
import {
15
+ HttpClient ,
15
16
HttpDownloadProgressEvent ,
16
17
HttpErrorResponse ,
17
18
HttpHeaderResponse ,
18
19
HttpParams ,
19
20
HttpStatusCode ,
21
+ provideHttpClient ,
22
+ withFetch ,
20
23
} from '../public_api' ;
21
24
import { FetchBackend , FetchFactory } from '../src/fetch' ;
22
25
@@ -416,6 +419,43 @@ describe('FetchBackend', async () => {
416
419
fetchMock . mockFlush ( 0 , 'CORS 0 status' ) ;
417
420
} ) ;
418
421
} ) ;
422
+
423
+ describe ( 'dynamic global fetch' , ( ) => {
424
+ beforeEach ( ( ) => {
425
+ TestBed . resetTestingModule ( ) ;
426
+ TestBed . configureTestingModule ( {
427
+ providers : [ provideHttpClient ( withFetch ( ) ) ] ,
428
+ } ) ;
429
+ } ) ;
430
+
431
+ it ( 'should use the current implementation of the global fetch' , async ( ) => {
432
+ const originalFetch = globalThis . fetch ;
433
+
434
+ try {
435
+ const fakeFetch = jasmine
436
+ . createSpy ( '' , ( ) => Promise . resolve ( new Response ( JSON . stringify ( { foo : 'bar' } ) ) ) )
437
+ . and . callThrough ( ) ;
438
+ globalThis . fetch = fakeFetch ;
439
+
440
+ const client = TestBed . inject ( HttpClient ) ;
441
+ expect ( fakeFetch ) . not . toHaveBeenCalled ( ) ;
442
+ let response = await client . get < unknown > ( '' ) . toPromise ( ) ;
443
+ expect ( fakeFetch ) . toHaveBeenCalled ( ) ;
444
+ expect ( response ) . toEqual ( { foo : 'bar' } ) ;
445
+
446
+ // We dynamicaly change the implementation of fetch
447
+ const fakeFetch2 = jasmine
448
+ . createSpy ( '' , ( ) => Promise . resolve ( new Response ( JSON . stringify ( { foo : 'baz' } ) ) ) )
449
+ . and . callThrough ( ) ;
450
+ globalThis . fetch = fakeFetch2 ;
451
+ response = await client . get < unknown > ( '' ) . toPromise ( ) ;
452
+ expect ( response ) . toEqual ( { foo : 'baz' } ) ;
453
+ } finally {
454
+ // We need to restore the original fetch implementation, else the tests might become flaky
455
+ globalThis . fetch = originalFetch ;
456
+ }
457
+ } ) ;
458
+ } ) ;
419
459
} ) ;
420
460
421
461
export class MockFetchFactory extends FetchFactory {
0 commit comments