xoxfreya
xoxfreya

Reputation: 31

Trying to run a test, but Jasmine keeps saying "No Provider for HTTPClient"

Trying to run some tests. On one component that is strictly just HTML, my tests work fine. I am now working on a component that uses an Api service on the page. However, I am running a simple test case to read HTML on the page first before I begin writing tests for the rest of the component.

My current issue is that whenever I run a test on my current component, it returns:

NullInjectorError: R3InjectorError(DynamicTestModule)
[ApiCallService -> HttpClient -> HttpClient]: NullInjectorError: No provider for HttpClient!
        

I have imported the HttpClient and HttpClientModule into app.module.ts. I have also imported it into the module that all the pages are running on for the application, and have also imported the HttpClientModule into the TestBedConfiguration itself on the spec.ts file of the component. I have tried using HttpClientTestingModule as well, but the exact same error keeps getting thrown.

The test case that I am trying to run is:

it('test', () => {
  const fixture = TestBed.createComponent(HomeComponent);
  fixture.detectChanges();
  const compiled = fixture.nativeElement as HTMLElement;
  expect(compiled.querySelector('p')?.textContent).toContain('Test');
});

Runs perfectly on another component, but not this one. If someone could point me in the right direction, that would be great. Had a few calls with my mentor, and they can't seem to figure it out, either.

Upvotes: 2

Views: 4709

Answers (1)

AliF50
AliF50

Reputation: 18849

Check out this guide. If you add HttpClientTestingModule to your imports array, I am thinking it should fix it for you.

That being said, since ApiCallService is an external service, I would mock that service.

Check this out on how to mock external dependencies in a component, in this instance it would be ApiCallService.

Upvotes: 1

Related Questions