Search code examples
angularjasmine

jasmine globally use httpClientTestingModule


Is there a way to globally inject httpClientTestingModule for each Testbed?

I unfortunately have a situation in which I cannot tell for certain when an XHR request is being made. My working theory is that it is a race condition based on randomized test execution caused by a library which we have in almost every component, (though I wouldn't claim to understand the problem and how this can be happening...)

With over 800 tests finding the bad apples proves to be rather difficult, and I would like to avoid implementing the module by hand over 100 times. Is there a nuke-em-all solution? A test should never go through to HttpCilent, so I thought maybe there is a global import command you can specify, in p.e. test.ts.


Solution

  • Yes we can.

    In test.ts we provide HttpClientTestingModule globally so that you don't have to import it in every TestBed setup:

      getTestBed().initTestEnvironment(
        [BrowserDynamicTestingModule, HttpClientTestingModule],
        platformBrowserDynamicTesting()
      );
    

    then after that you can add an afterEach in test.ts that will call the verify method:

    afterEach(() => {
      const httpController = TestBed.get(
        HttpTestingController
      ) as HttpTestingController;
      httpController.verify();
    });
    

    Note: in recent version of Angular swap TestBed.get with TestBed.inject.

    Working example: https://stackblitz.com/edit/angular-kyvzmt?file=src%2Fmain.ts. (Notice main.ts and http-client.specs.ts)