I have the below method that listens to a custom event and sets the focus of the element. I want to write a unit test for this method. I am trying to mock the focus element focus and using fakeAsync to provide a little delay and also mocking the renderer listener but the coverage is not getting through this method.
listenToModalCloseEvent() {
this.modalListenerFn = this.renderer.listen(document, 'popupClosed', () => {
if (this.focusElement) {
setTimeout(() => {
this.focusElement.focus();
}, 0);
}
});
}
here is what I have trid,
it('should call listenToModalCloseEvent', fakeAsync(() => {
dummyElement.dispatchEvent(new Event('popupClosed', { bubbles: true }));
service.focusElement = dummyElement;
service.listenToModalCloseEvent();
const spy = spyOnProperty(service, 'focusElement').and.returnValue({ focus: () => {}});
spyOn((service as any).renderer, 'listen').and.callThrough();
tick(100);
expect(service.focusElement).toBeDefined();
expect(spy).toHaveBeenCalled();
}))
Don't where I am wrong