Issue
I am getting the following error when running my tests using ng test
in Angular. I have read similar questions but I don't think it is the same problems given that I tried the solutions in the answers with no luck.
ApiService > should be created
NullInjectorError: R3InjectorError(DynamicTestModule)
[ApiService -> HttpClient -> HttpHandler -> HttpHandler]:
NullInjectorError: No provider for HttpHandler!
error properties: Object({ ngTempTokenPath: null, ngTokenPath:
[ 'ApiService', 'HttpClient', 'HttpHandler', 'HttpHandler' ] })
Here is my code:
import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
import { EnvServiceProvider } from './env.service.provider';
import { HttpClient } from '@angular/common/http';
describe('ApiService', () => {
let service: ApiService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ApiService, EnvServiceProvider, HttpClient]
});
service = TestBed.inject(ApiService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
Solution
You need to call provideHttpClient()
instead of just providing the HttpClient
.
provideHttpClient()
will define the providers for HttpClient
, HttpHandler
, HttpBackend
, the interceptors etc.
import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
import { EnvServiceProvider } from './env.service.provider';
//import { HttpClient } from '@angular/common/http';
import { provideHttpClient } from '@angular/common/http';
describe('ApiService', () => {
let service: ApiService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ApiService, EnvServiceProvider, provideHttpClient()]
});
service = TestBed.inject(ApiService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.