【发布时间】:2017-02-15 02:12:01
【问题描述】:
我正在使用 Angular 2 final (2.0.1)。 我有一个提供服务的组件。它是唯一使用它的,这就是它提供它而不是包含模块的原因,它也被注入到构造函数中。
@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");
});
});
但是,当我将服务提供声明从组件移动到包含模块时,测试通过了。
我认为这是因为 TestBed 测试模块定义了模拟服务,但是在创建组件时 - 它用实际实现覆盖了模拟...
有人知道如何测试提供服务的组件并使用模拟服务吗?
【问题讨论】: