要解决“NullInjectorError: No provider for HttpClient!”错误,您可以按照以下步骤进行操作:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule],
...
})
export class AppModule { }
import { HttpClientTestingModule } from '@angular/common/http/testing';
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
...
})
.compileComponents();
}));
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('YourService', () => {
let service: YourService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [YourService]
});
service = TestBed.get(YourService);
httpTestingController = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpTestingController.verify();
});
it('should make a GET request', () => {
const testData = { message: 'test' };
service.getData().subscribe(data => {
expect(data).toEqual(testData);
});
const req = httpTestingController.expectOne('your-url');
expect(req.request.method).toEqual('GET');
req.flush(testData);
});
});
以上是解决“NullInjectorError: No provider for HttpClient!”错误的一般步骤。根据您的具体代码和测试设置,您可能需要进行一些适应性调整。
下一篇:Angular 6服务注入异常