Sub topic 10
Testing Dispatched Events with Jest
This chapter shows how to test that a Lightning Web Component dispatches the right CustomEvent. It assumes you can write a child component that calls dispatchEvent, you know how @api properties work, and you have used describe, it, and expect in Jest. You also need @salesforce/sfdx-lwc-jest set up in your project, so that npm run test:unit runs your tests.
What you are testing
A child component's event contract has three parts:
- The event name, such as
productselected. - The payload in
event.detail. - The propagation settings:
bubblesandcomposed.
A good unit test checks the contract from the outside. It does not read private fields or call handler methods directly. It mounts the component, listens on the host element the way a parent would, triggers the user action, and inspects what arrived.
The component under test is the ProductTile from earlier in this tutorial.
// 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>The test flow
The diagram shows the order of steps in the test. The listener must be attached before the click, because the event fires synchronously during click().
A first 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');
});
});Walk through it line by line:
createElementbuilds the component the way the framework does, and{ is: ProductTile }names the class to use. The tag name you pass is only a label. It does not need to match anything in a template.- Setting
element.productId = 'p1'uses the public@apiproperty, just as a parent template would. document.body.appendChild(element)connects the component. This runsconnectedCallbackand renders the template. Until the element is attached, thebuttondoes not exist.jest.fn()creates a mock function that records every call. It plays the role of the parent's handler.element.addEventListenerlistens on the host element. This is the same element a parent would putonproductselectedon.element.shadowRoot.querySelector('button').click()simulates the user. In Jest, the test file can readshadowRootof a component it created, even though code in other components cannot.handler.mock.calls[0][0]is the first argument of the first call, which is the event object.
The afterEach cleanup removes components from the DOM so one test cannot see leftovers from another. Without it, document.body accumulates elements across tests, and any later document.querySelector can find the wrong one.
Checking the whole contract
The first test covers name and payload. Add tests for the other parts of the contract, so a later refactor cannot change them silently.
// productTile.contract.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
function mountTile(props = {}) {
const element = createElement('c-product-tile', { is: ProductTile });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-product-tile event contract', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('does not dispatch before a click', () => {
const element = mountTile({ productId: 'p1' });
const handler = jest.fn();
element.addEventListener('productselected', handler);
expect(handler).not.toHaveBeenCalled();
});
it('dispatches once per click', () => {
const element = mountTile({ productId: 'p1' });
const handler = jest.fn();
element.addEventListener('productselected', handler);
const button = element.shadowRoot.querySelector('button');
button.click();
button.click();
expect(handler).toHaveBeenCalledTimes(2);
});
it('uses the current productId at click time', () => {
const element = mountTile({ productId: 'p1' });
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.productId = 'p2';
element.shadowRoot.querySelector('button').click();
expect(handler.mock.calls[0][0].detail.productId).toBe('p2');
});
it('does not bubble or cross shadow boundaries by default', () => {
const element = mountTile({ productId: 'p1' });
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
const event = handler.mock.calls[0][0];
expect(event.bubbles).toBe(false);
expect(event.composed).toBe(false);
});
});The last test is useful because the defaults are easy to change by accident. If someone adds bubbles: true to fix one parent, every ancestor starts receiving the event. A test that pins bubbles and composed turns that change into a visible, deliberate decision.
Testing the bubbling variant
If a component deliberately sets bubbles: true, test that choice too. The test below uses a throwaway dispatch to show how to observe bubbling on the host.
// bubbling.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('bubbling observation', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('lets you observe an event on document.body when it bubbles and is composed', () => {
const element = createElement('c-product-tile', { is: ProductTile });
document.body.appendChild(element);
const bodyHandler = jest.fn();
document.body.addEventListener('probe', bodyHandler);
element.dispatchEvent(
new CustomEvent('probe', { bubbles: true, composed: true })
);
expect(bodyHandler).toHaveBeenCalledTimes(1);
document.body.removeEventListener('probe', bodyHandler);
});
it('does not reach document.body when the event does not bubble', () => {
const element = createElement('c-product-tile', { is: ProductTile });
document.body.appendChild(element);
const bodyHandler = jest.fn();
document.body.addEventListener('probe', bodyHandler);
element.dispatchEvent(new CustomEvent('probe'));
expect(bodyHandler).not.toHaveBeenCalled();
document.body.removeEventListener('probe', bodyHandler);
});
});For your own component, the pattern is the same. Attach a listener on an ancestor, such as document.body, trigger the real user action, and assert whether the listener ran. Remove any listener you put on document.body, because it outlives the test.
Testing a parent that handles the event
A parent test checks the other half of the contract: that the handler reads event.detail and updates the view. You do not need to click the real child. You can dispatch the event yourself on the child element inside the parent's shadow root.
// productList.test.js
import { createElement } from 'lwc';
import ProductList from 'c/productList';
describe('c-product-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the selected product id', async () => {
const element = createElement('c-product-list', { is: ProductList });
document.body.appendChild(element);
const tile = element.shadowRoot.querySelector('c-product-tile');
tile.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: 'p1' }
})
);
await Promise.resolve();
const text = element.shadowRoot.querySelector('p').textContent;
expect(text).toBe('Selected: p1');
});
});Two details matter here:
- The test dispatches on the
c-product-tileelement, because that is where theonproductselectedattribute is attached. Dispatching onelement(the parent host) would not trigger the handler. await Promise.resolve()waits one microtask. SettingselectedIdin the handler schedules a re-render, and the DOM updates after the current synchronous work finishes. Reading the text before awaiting gives you the old value.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot read properties of null (reading 'click')` | The query ran before the element was appended, or the selector is wrong | Call `appendChild` first, and check the selector against the template |
| Handler never called | Listener attached after the click, or the event name differs in case or spelling | Attach the listener first, and match the name exactly |
| Handler called but `detail` is `undefined` | The component dispatched without a `detail` option | Check the `CustomEvent` constructor call |
| `handler.mock.calls[0]` is `undefined` | Same as "never called", and the test then reads the empty list | Assert `toHaveBeenCalledTimes(1)` before reading `mock.calls` |
| Parent text still shows the old value | The test did not wait for the re-render | `await Promise.resolve()` before asserting on the DOM |
| Results differ between tests | Components left in `document.body` | Clean up in `afterEach` |
Asserting on the payload shape
toBe compares by identity, which is right for strings and numbers. For object payloads, use toEqual, which compares structure. If you want to allow extra fields, use toMatchObject.
// payloadShape.test.js
describe('payload matching', () => {
const detail = { productId: 'p1', quantity: 2 };
it('toEqual requires the exact structure', () => {
expect(detail).toEqual({ productId: 'p1', quantity: 2 });
});
it('toMatchObject allows extra fields', () => {
expect(detail).toMatchObject({ productId: 'p1' });
});
it('toBe fails for two separate objects with the same content', () => {
expect(detail).not.toBe({ productId: 'p1', quantity: 2 });
});
});Prefer toEqual on the whole detail when the payload is small and stable. It catches an accidentally added field. Prefer toMatchObject when other teams may add fields later and your test should not break.
What a unit test cannot tell you
Jest runs components in a simulated DOM. It confirms that your component dispatches the event you designed. It does not confirm that a particular parent in an org listens for the same name. If the parent's attribute is onproductselect and the child dispatches productselected, both unit tests can pass while the real page does nothing. Guard against this by keeping the event name in one documented place, and by testing the parent with an event of the same name, as in the previous section.
Exercise
A child component's test attaches a listener with element.addEventListener('save', handler), then calls element.shadowRoot.querySelector('button').click(). The assertion expect(handler.mock.calls[0][0].detail.id).toBe('a1') throws TypeError: Cannot read properties of undefined (reading '0'). What does this error tell you, and what assertion would give a clearer failure?
Show answer
handler.mock.calls is empty, so handler.mock.calls[0] is undefined, which means the handler was never called. Possible causes are a mismatched event name, a listener attached after the click, or a button that never dispatches. Add expect(handler).toHaveBeenCalledTimes(1) before the payload assertion. If the handler was not called, that assertion fails with a message that says so.
Exercise
You test a parent component by calling element.dispatchEvent(new CustomEvent('productselected', { detail: { productId: 'p1' } })) on the parent's host element, but the parent's handler never runs. Why, and how do you fix it?
Show answer
The onproductselected attribute is attached to the c-product-tile element inside the parent's template, so only an event dispatched on that element triggers the handler. Query it with element.shadowRoot.querySelector('c-product-tile') and call dispatchEvent on the result. Then await Promise.resolve() before checking the rendered output.
Exercise
Write the assertions that would fail if someone changed a child's event to use bubbles: true without telling anyone.
Show answer
After capturing the event with a mock listener, assert expect(event.bubbles).toBe(false) and expect(event.composed).toBe(false), where event is handler.mock.calls[0][0]. Optionally, attach a second listener on document.body and assert it was not called after the click.