Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Observable.fromEvent

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

like image 399
Sachila Ranawaka Avatar asked Feb 08 '18 04:02

Sachila Ranawaka


1 Answers

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 :)

like image 112
Valex Avatar answered Oct 04 '22 15:10

Valex