Angular 6-NullInjectorError:在单元测试中没有HttpClient的提供程序 [英] Angular 6 - NullInjectorError: No provider for HttpClient in unit tests
本文介绍了Angular 6-NullInjectorError:在单元测试中没有HttpClient的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在如下服务中导入并使用 HttpClient
:
I am importing and using HttpClient
in a service as follows:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get("url...");
}
}
但是,当我为单元测试运行 ng test
时,当这些测试使用该服务时,我会收到错误消息:
However, when I run ng test
for my unit tests, and when those tests use the service, I am getting the error:
错误:StaticInjectorError(DynamicTestModule)[HttpClient]:StaticInjectorError(平台:核心)[HttpClient]:NullInjectorError:HttpClient没有提供程序!
HTTP上的Angular 6文档只是说可以我在上面所做的.
The Angular 6 documentation on HTTP just says to do what I did above.
推荐答案
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { myService } from './myservice';
describe('myService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [myService]
}));
it('should be created', () => {
const service: myService = TestBed.get(myService);
expect(service).toBeTruthy();
});
it('should have getData function', () => {
const service: myService = TestBed.get(myService);
expect(service.getData).toBeTruthy();
});
});
这篇关于Angular 6-NullInjectorError:在单元测试中没有HttpClient的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文