我想为服务编写单元测试。第一次测试失败, 出现此错误:
NullInjectorError:StaticInjectorError(DynamicTestModule)[HttpClient]:
StaticInjectorError(平台:核心)[HttpClient]:
NullInjectorError:HttpClient没有提供程序!
我不明白这一点,因为在被测试的服务中,我没有在任何地方使用HttpClient
。
规格文件:
export class MockApiService {
private apiUrl = 'apiUrl';
get(endPoint: string) {
return new Observable<{data: 'data'}>();
}
post(endPoint: string, data: any) {
return new Observable<{data: 'data'}>();
}
patch(endPoint: string, data: any) {
return new Observable<{data: 'data'}>();
}
getApiUrl() {
return this.apiUrl;
}
}
describe('TimeSlotService', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
TimeSlotService,
{ provide: ApiService, useValue: MockApiService }
]
}));
it('should be created', () => {
const service: TimeSlotService = TestBed.get(TimeSlotService);
expect(service).toBeTruthy();
});
});
时隙服务文件:
@Injectable({
providedIn: 'root'
})
export class TimeSlotService {
constructor(private api: ApiService) { }
static toPeriods(timeSlots: TimeSlot[]): string[] {
const periods: string[] = [];
for (const timeSlot of timeSlots) {
periods.push(timeSlot.start + ' - ' + timeSlot.end);
}
return periods;
}
getTimeSlots() {
return this.api.get('timeSlots')
.pipe(map(ApiService.extractData));
}
}
我在这里想念什么?
答案 0 :(得分:1)
该错误具有误导性,您在TestBed提供程序列表中缺少正在测试的服务。
答案 1 :(得分:0)
Angular告诉您它无法注入HttpClient
,因此您可以轻松导入导入HttpClientTestingModule
describe('TimeSlotService', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
{ provide: ApiService, useValue: MockApiService }
],
imports: [ HttpClientTestingModule ]
}));
it('should be created', () => {
const service: TimeSlotService = TestBed.get(TimeSlotService);
expect(service).toBeTruthy();
});
});
此修补程序不能解决您对HttpClient的误解。也许您不应该使用useValue
,而是使用useClass