Angular注入失败



我正在尝试创建一个Angular单元测试,但是马上就失败了。

我已经看了一下这个和这个这个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没有提供程序!

My .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) { }
}

您只需要导入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();
});
});

是的,就像tilo说的,它应该能工作。并尽量使你的beforeEach-async()

试试这个——稍微修改一下(参见声明部分):

import { TestBed } from '@angular/core/testing';
import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('ContactsService', () => {

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ContactsService],
imports: [ HttpClientTestingModule]
})
.compileComponents();
}));

});

最新更新