I have a angular component, inside the template I have a stencilJS component which is emitting an event which I'm handling in the parent component. I'm trying to write unit-test cases for the "handleEvent
" method but I couldn't get the component instance of the component by using By.directive(platformNavbarComponent)
, spyOn().and.callFake(...)
also did not work or could find any information relating to my problem.
Parent.component.html
<cel-platform-navbar
(platformSelected)="handleEvent($event)">
</cel-platform-navbar>
Parent.component.ts
handleEvent(ev) {
console.log(ev)
}
this is the test case I have written and I'm getting the following error
Expected spy handleEvent to have been called
this is the test case
fit('should call handler for "platformSelected" event', () => {
const event = new CustomEvent('platformSelected', {detail:{navigationUrl: 'abc'}});
fixture.detectChanges();
const spy = spyOn(component, 'handleEvent').and.callThrough();
window.dispatchEvent(event);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
});
Try using triggerEventHandler
.
fit('should call handler for "platformSelected" event', () => {
const spy = spyOn(component, 'handleEvent').and.callThrough();
const celPlatformNavbar = fixture.debugElement.query(By.css('cel-platform-navbar'));
celPlatformNavbar.triggerEventHandler('platformSelected', { detail:{navigationUrl: 'abc' }});
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
});
A good article with a little bit on triggerEventHandler
link here.