你怎么能模拟DOM窗口事件?

时间:2017-12-08 20:45:18

标签: angular typescript jasmine

在我的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事件,但不确定如何触发事件......

1 个答案:

答案 0 :(得分:1)

只需使用BehaviorSubject模拟服务并触发next调用,以确保调用您的侦听器。

像这样:

&#13;
&#13;
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;
&#13;
&#13;