Search code examples
angularjestjsangular18angular-jest

HttpClientTestingModule is deprecated, how to replace it?


After upgrading my application to Angular 18.0.4, my test classes say:

'HttpClientTestingModule' is deprecated. Add provideHttpClientTesting() to your providers instead.

Therefore I adapted my code as follows:

        await TestBed.configureTestingModule(
            {
                imports: [
                    AssetDetailsComponent,
                ],
                providers: [
                    // replacement for HttpClientTestingModule:
                    provideHttpClientTesting() 
                ]
            })
            .compileComponents();

However, when I run the tests, I get the following error:

NullInjectorError: R3InjectorError(Standalone[AssetDetailsComponent])[InventoryActionService -> InventoryActionService -> _HttpClient -> _HttpClient]:
      NullInjectorError: No provider for _HttpClient!

If I use provideHttpClient() instead of provideHttpClientTesting() it works, yet I doubt that this is best practice. What is the correct solution to this issue?


Solution

  • Also add provideHttpClient() before provideHttpClientTesting()

    providers: [
       provideHttpClient(),
       provideHttpClientTesting() 
    ]
    

    As mentioned in the docs.