我试图模拟组件测试的服务。 这里我的服务:在单元测试中嘲笑服务
@Injectable()
export class LoginService {
constructor(public http: Http) { }
getLanguages() {
return this.http.get('the-url')
.map((res: Response) => res.json());
}
...
注:我的组件调用构造函数中的这个方法(构造比较时加载的语言)。
然后我试图嘲笑它:
class MockLoginService {
getLanguages() {
return Observable.of(
[
{
'name': 'English (USA)',
'locale': 'en-US'
},
{
'name': 'Español',
'locale': 'es-US'
}
]
);
}
而且我的组件单元测试:
it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
tcb
.overrideProviders(LoginComponent, [ provide(LoginService, { useClass: MockLoginService })])
.createAsync(LoginComponent).then((fixture) => {
let element = fixture.nativeElement;
let loginInstance = fixture.componentInstance;
fixture.detectChanges();
expect(loginInstance._loginService.getLanguages).toHaveBeenCalled();
expect(element.querySelectorAll('option').length).toBe(5);
});
}));
问题:
我看到我的模拟服务被称为和接收的数据是正确的,但我的2个测试被跳过!这里是日志:
angular2-polyfills.js:528 Unhandled Promise rejection: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out ; Zone: ; Task: Promise.then ; Value: Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out(…)
我承诺服务执行异步和测试丢失某处。 (......)
我尝试了fakeAsync与(),但没有捕获(承诺)错误:'期望'被用于没有当前规范,这可能是因为异步测试超时剔 - 没有成功。 在此先感谢!
试试'injectAsync([TestComponentBuilder],''而不是'inject([TestComponentBuilder],..' –