我正在尝试创建一个 Angular 单元测试,但立即失败了。
我已经查看了 this 和 this 这个 SO,这似乎正是我正在努力解决的问题,但是在尝试了那里提到的修复之后,我仍然没有正确.
这是我的代码:
import { TestBed } from '@angular/core/testing';
import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
describe('ContactsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, ContactsService, HttpClient],
})
.compileComponents();
});
});
当我运行 ng 测试时,出现此错误:
<块引用>NullInjectorError: R3InjectorError(DynamicTestModule)[ContactsService -> HttpClient -> HttpClient]: NullInjectorError: 没有 HttpClient 的提供者!
我的 .ts,为了完整性:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Entry } from '../classes/entry';
import { EntrySearch } from '../classes/entrySearch';
@Injectable({
providedIn: 'root'
})
export class ContactsService {
constructor(private http: HttpClient) { }
}
答案 0 :(得分:0)
您只需要导入 HttpClientTestingModule
并提供您的 ContactsService
:
import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
describe('ContactsService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ ContactsService ]
}));
it('should be created', () => {
const service: ContactsService = TestBed.inject(ContactsService);
expect(service).toBeTruthy();
});
});
答案 1 :(得分:0)
是的,就像 tilo 说的那样,它应该有效。
并尝试使您的 GBP
- beforeEach
。
试试这个 - 稍微修改一下(见声明部分):
async()