Reputation: 21458
In my ng4 app, I have a service that exposes an Observable over the window focus event. How would you go about testing this (I am using Jasmine, but that's not very important)?
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();
}
My approach is to mock the window object and to trigger fire the onfocus event, but am unsure of how to trigger the event...
Upvotes: 1
Views: 683
Reputation: 3315
Just mock the service using a BehaviorSubject
and trigger a next
call to ensure your listeners are invoked.
Like this:
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
})
Upvotes: 1