我正在使用jasmine编写一些angular2单元测试,并为组件进行单元测试。出于某种原因,当我尝试使用TestBed
类实例化组件时,我得到了依赖注入错误。
LoginComponent
:
import { Component } from '@angular/core';
import { LoginService } from './login.service';
@Component({
selector: 'login',
template: require('./login.template.pug'),
styles: [require('./style.scss')],
providers: [LoginService]
})
export class LoginComponent {
public username: string;
public password: string;
constructor(private loginService: LoginService) {
}
public login(username, password) {
this.loginService.login(username, password)
.then((token: string) => {
})
}
}
LoginComponentTest
:
import { TestBed, inject, async, ComponentFixture } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';
import { LoginService } from './login.service';
import { BrowserModule } from '@angular/platform-browser';
describe('LoginComponent', () => {
class MockClass {
get(url): Promise<any> {
throw Error('not implemented');
};
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
LoginComponent
],
providers: [
LoginComponent,
{ provide: LoginService, useClass: MockClass },
],
imports: [
FormsModule,
BrowserModule,
ReactiveFormsModule
]
})
}));
it('will let user login', async(() => {
TestBed.compileComponents()
.then(() => {
let fixture: ComponentFixture<LoginComponent> = TestBed.createComponent(LoginComponent);
});
}));
});
该行
let fixture: ComponentFixture<LoginComponent> = TestBed.createComponent(LoginComponent);
给出以下错误:
Chrome 57.0.2987(Mac OS X 10.12.3)LoginComponent将允许用户登录 FAILED错误:DI错误 在NoProviderError.ZoneAwareError(webpack:///~/zone.js/dist/zone.js:958:0&lt; - 配置/规格-bundle.js:75553:33)
我声明了LoginComponent
及其自己的依赖关系LoginService
。
有关正在发生的事情的任何想法?
答案 0 :(得分:2)
好的,我想通了,有点儿。显然,该问题与providers
中的LoginComponent
声明有关:
providers: [LoginService]
一旦我将其移出LoginComponent
并进入AppModule
,事情就开始起作用了。有兴趣知道为什么测试不能在组件本身内部声明它。