Sub topic 10
Testing Dispatched Events with Jest
This chapter assumes you can build a child component that dispatches a CustomEvent and a parent that handles it. You should also know basic Jest syntax (describe, it, expect) and have @salesforce/sfdx-lwc-jest set up in your project.
What a test needs to prove
A child component's contract with its parent has three parts: the event name, the payload in event.detail, and the action that triggers it. A good test checks all three without involving the parent. The test plays the parent's role. It listens on the child's host element, triggers the user action, and inspects what arrived.
Setting up the test
The test file sits in a __tests__ folder next to the component. It uses createElement from lwc to build the component and attach it to the document.
Here is the child component under test:
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId }
})
);
}
}<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>And the test:
// productTile.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('c-product-tile', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('dispatches productselected with the product id', () => {
const element = createElement('c-product-tile', { is: ProductTile });
element.productId = 'p1';
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.productId).toBe('p1');
});
});The afterEach cleanup is not in the minimal example, but it keeps one test's DOM from leaking into the next.
How the test works
createElement('c-product-tile', { is: ProductTile })builds the component. The tag name is a label for the test. It does not need to be registered anywhere.- Setting
element.productId = 'p1'works becauseproductIdis decorated with@api. Private fields cannot be set this way. document.body.appendChild(element)connects the component. The template renders andconnectedCallbackruns.jest.fn()creates a mock function that records every call.element.addEventListener(...)attaches the mock to the host element. This is the same element the child passes tothis.dispatchEvent.element.shadowRoot.querySelector('button').click()simulates the user. The click fires the native event, which runshandleClick, which dispatches the custom event.
The click handler and the dispatch both run synchronously, so the assertions can follow the click directly.
Reading the recorded call
handler.mock.calls is an array with one entry per call. Each entry is the list of arguments. So handler.mock.calls[0][0] is the first argument of the first call, which is the event object. From there you read event.detail just as a parent handler would.
A shorter check on the payload is possible with toHaveBeenCalledWith, but it must match the whole event object, which is awkward. Reading mock.calls keeps the assertion focused on detail.
Common errors
- The handler is never called. The listener must go on the host
element, not on the button. Withoutbubbles: true, the event does not travel past the host element. Listening inside the shadow root misses it. querySelectorreturns null. Query throughelement.shadowRoot, notdocument. The template content is inside the shadow tree.- The payload is
undefined. Check that you set the@apiproperty before or after appending, and that the property name matches the component. A misspelled property is silently set as a plain expando on the element. - Assertions run before a re-render. The click path here is synchronous. If your test checks rendered DOM after changing a property, await a resolved promise first:
await Promise.resolve();.
Testing a bubbling event
If the child sets bubbles: true, you can add a second test that listens on a wrapper element. Append a div to document.body, append the component into it, and attach the listener to the div. The mock should fire once. If you also want to prove it does not cross a shadow boundary, you can omit composed and listen on document.body. The mock should not fire.
Exercise
In the test above, why is the listener attached with element.addEventListener and not on the button found through element.shadowRoot?
Show answer
The component calls this.dispatchEvent, which fires the event on the host element, not on the button. The event does not bubble, so a listener on the inner button would never see it. The test must listen where a real parent would: on the host element.
Exercise
Write the assertion line that checks the handler received a detail object whose productId is 'p2', assuming the handler was called once.
Show answer
expect(handler.mock.calls[0][0].detail.productId).toBe('p2');