How do we test Observable.fromEvent
using jasmine
@ViewChild('d')
private inputDatePicker: NgbInputDatepicker;
this.subscription = Observable.fromEvent(document, 'click').subscribe((event: KeyboardEvent) => {
if (!this.eRef.nativeElement.contains(event.target)) {
this.inputDatePicker.close();
}
});
ngOnDestroy() {
this.subscription.unsubscribe();
}
I'm using ngb-date-picker
and using fromevent
to catch the document click and close the date picker
I think that your best guess in this scenario is first of all not get document as global, but inject it into your component/directive/injectable (angular offer a method to provide it by using -> @Inject(DOCUMENT)). At this point you can mock it passing you own implementation. From there you add method like this to your mock
{
addEventListener: jasmine.createSpy('addEvent').and.callFake((eventName: string, cb: () => void) => {
imageListeners[eventName] = cb;
}),
removeEventListener: jasmine.createSpy('removeEvente').and.callFake((eventName: string) => {
delete imageListeners[eventName];
})
}
(ofc appropriate for your case this is just some code that i've written for a simliar situation)
and when you need to trigger your method
addEventListener.calls.argsFor
and so on. I've written this answer under the assumption that you use jasmine as testing suite, but should be similar with other suite just the methods to be different. Hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With