mateuszs
mateuszs

Reputation: 165

Constructor injection affecting basic tests issue

I have Angular6 project with following constructor in component:

constructor(@Inject('httpClient')private httpClient: HttpClient) {
}

It however may be affecting results of component-generated tests(e.g. "should create the app") with message related to:

Error: StaticInjectorError(DynamicTestModule)[httpClient]: 
StaticInjectorError(Platform: core)[httpClient]: 
NullInjectorError: No provider for httpClient!

I have already tried importing HttpClientModule and also HttpClientTestingModule but it did not resolve issue. Code related to describing component:

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [
    AppComponent
        ],
  imports: [
    FormsModule,
    HttpClientModule,
    HttpClientTestingModule
  ]
}).compileComponents();
}));

What steps can I take to get rid of the error message?

Upvotes: 0

Views: 32

Answers (2)

mateuszs
mateuszs

Reputation: 165

In case you are facing constructor related testing issue and there is message involving InjectorError you can add imports with configureTestingModule.

Example:

TestBed.configureTestingModule({
imports: [
  HttpClientModule
]
})

Upvotes: 1

RoadEx
RoadEx

Reputation: 541

Try to mock the service. First, you create the dummy service :

class MockHttpClient { }

Then, in the TestBed providers, instead of HttpClient, you use the mocked service.

providers: [         
    { provide: HttpClient, useClass: MockHttpClient },
]

This way, you won't have to implement all the dependencies of the service. Of course, you won't be able to use the real HttpClient functions, but that shouldn't be a problem as you should only test the component and not the service here.

Upvotes: 0

Related Questions