4
我正在使用Angular 2 final(2.0.1)。 我有一个提供服务的组件。它是唯一使用它的人,这就是为什么它提供它而不是包含模块,并且它也被注入到构造函数中。提供服务的组件的Angular 2测试规范
@Component({
selector: 'my-comp',
templateUrl: 'my-comp.component.html',
styleUrls: ['my-comp.component.scss'],
providers: [MyService],
})
export class MyComponent {
constructor(private myService: MyService) {
}
}
当我尝试实现规范时,它失败。
describe("My Component",() => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{
provide: MyService,
useClass: MockMyService
},
]
});
this.fixture = TestBed.createComponent(MyComponent);
this.myService = this.fixture.debugElement.injector.get(MyService);
});
describe("this should pass",() => {
beforeEach(() => {
this.myService.data = [];
this.fixture.detectChanges();
});
it("should display",() => {
expect(this.fixture.nativeElement.innerText).toContain("Health");
});
});
但是,当我将组件的服务提供声明移动到包含模块时,测试通过。
我想这是因为测试床测试模块定义模拟服务,而是创建组件时 - 它会覆盖与实际执行的模拟...
没有人有任何想法如何测试组件提供服务并使用模拟服务?
完美!不知道我是如何在文档中错过的:) –