在我的ng4应用程序中,我有一个服务,通过窗口焦点事件公开Observable。你会如何测试这个(我使用的是Jasmine,但这不是很重要)?
constructor(@Inject('Window') private window: Window) {
this.window.onfocus = () => {
this.onFocusSubject.next();
};
}
// how can I test that the onFocus Observable is triggered
// when window.onfocus is fired?
public onFocus(): Observable<any> {
return this.onFocusSubject.asObservable();
}
我的方法是模拟窗口对象并触发onfocus事件,但不确定如何触发事件......
答案 0 :(得分:1)
只需使用BehaviorSubject
模拟服务并触发next
调用,以确保调用您的侦听器。
像这样:
const serviceStub = {
windowEvent: new BehaviorSubject(null);
}
// in your test:
it('should trigger an event listener: ', () => {
const service = componentInstance.injector.get(Service);
service.windowEvent.next(new FocusEvent('focus'));
// write your test logic here
})
&#13;