【发布时间】:2016-05-21 14:49:22
【问题描述】:
我目前正在为我的一个组件编写单元测试。特别是,我有login(): void 功能。这是简化的逻辑:
login(): void {
this.showSpinner = true;
this.userService.login(loginData)
.subscribe(result => {
this.showSpinner = false;
}
)
}
我正在努力编写一个测试,在调用 userService.login 之前检查 showSpinner 属性是否设置为 true。
这是我的测试:
it('should display the spinner when the form is being saved',
inject([TestComponentBuilder], fakeAsync((tcb: any) => {
createComponent(tcb).then((fixture:ComponentFixture<any>) => {
fixture.componentInstance.login();
expect(fixture.componentInstance.showSpinner).toBe(true);
tick();
});
})));
});
这个测试失败了,因为.subscribe 被立即解决/运行(我尝试在我的组件中注释掉this.showSpinner = false,并且测试通过了)。
在我的 userService 模拟中,对于 login 方法模拟,我有以下内容:
this.loginSpy = this.spy('login').andReturn(Observable.of(this));
this 是 mockUserService。
我确信我正在正确地模拟 userService,特别是 userService 上的 login 方法,因为我对该组件进行了其他测试,这些测试运行正常。
我还尝试从我的间谍返回Observable.of(this).delay(1),然后在我的测试中调用tick(1)。然而,这会导致不一致的行为,因为有时我的测试通过了,但有时我收到一条错误消息:
Error: 1 periodic timer(s) still in the queue.
如何测试.subscribe() 之前的逻辑?
【问题讨论】:
标签: unit-testing angular rxjs observable angular2-testing