I'm trying to test a click event originated from an icon (<i>
) in a Stencil component. The thing is I am able to debug the test and I see that the test triggers the correct method on the component, but Jest is not able to detect\register the event and the toHaveBeenCalled()
method fails.
input.spec.jsx
it("dispatches icon click event", async () => {
const page = await newSpecPage({
components: [Input], //just the component name
template: () => (<input-fields value="some input value"></input-fields>),
});
const eventSpy = jest.fn();
page.win.addEventListener('input-field-search-event', eventSpy);
await page.root.shadowRoot.querySelector('.icon-container').click();
await page.waitForChanges();
expect(eventSpy).toHaveBeenCalled();
});
input.tsx
private dispatchSearchEvent(e){
//i can stop ay this point with a break point and the data passed by the test is correct
this.tipInputEnterEvent.emit({type: "input-field-search-event", event: e, data: this.value});
}
the error
● Input tests › dispatches icon click event
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
334 | await page.root.shadowRoot.querySelector('.icon-container').click();
335 | await page.waitForChanges();
> 336 | expect(eventSpy).toHaveBeenCalled();
| ^
337 | });
338 |
339 | });
By default the name of custom events is the property name, in your case tipInputEnterEvent
. So the listener should instead be:
page.win.addEventListener('tipInputEnterEvent', eventSpy);
You can also change the event name if you want:
@Event({ eventName: 'input-field-search-event' }) tipInputEnterEvent: EventEmitter;