Sub topic 9
Test user interaction and custom events
A Lightning web component takes input from the user and sends output to its parent. The input arrives as clicks, typing, and selections. The output leaves as custom events. This chapter shows how to simulate the input and check the output in a Jest test.
This chapter assumes you can already create a component with createElement, attach it to document.body, query its shadow root, and use await Promise.resolve() to wait for re-rendering. It also assumes you know how dispatchEvent and CustomEvent work in a component.
What a test should check
A test for user interaction follows four steps:
- Create the component and attach it to the document.
- Register a listener for the events you expect.
- Act as the user would, for example by clicking a button.
- Assert on the DOM and on what the listener received.
The test never calls handleClick directly. Handlers are private implementation details. If you rename one, the component still behaves the same, and the test should still pass. Triggering the real DOM event also checks that the template wires the handler to the right element.
The component under test
The examples use the counter component. Its template is in force-app/main/default/lwc/counter/counter.html:
<template>
<p class="count">{count}</p>
<button onclick={handleClick}>Add</button>
</template>Its class has a public step property and a count field. It dispatches a countchange event on each click:
import { LightningElement, api } from 'lwc';
export default class Counter extends LightningElement {
@api step = 1;
count = 0;
handleClick() {
this.count += this.step;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}Simulate a click and capture the event
Calling click() on an element fires a real click event in jsdom, the simulated browser that Jest uses. The component's onclick handler runs synchronously.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('adds the step to the count and fires countchange', async () => {
const element = createElement('c-counter', { is: Counter });
element.step = 2;
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('countchange', handler);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('2');
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.count).toBe(2);
});
});jest.fn() creates a mock function that records every call. You attach it with addEventListener, just as a parent component would. Each entry in handler.mock.calls is an array of arguments, so mock.calls[0][0] is the event object from the first call.
The sequence of calls is shown below.
Which assertions need the `await`
Event dispatch is synchronous. The listener has already run when click() returns, so you could check handler without waiting. The DOM is different, because LWC re-renders in a microtask after a reactive field changes. You need the await before reading .count.
Putting the await before all the assertions is a simple habit that always works. You can also split the checks, as in this example:
button.click();
expect(handler).toHaveBeenCalledTimes(1); // already true, no wait needed
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('2');Click more than once
Clicking in a loop lets you check that state accumulates and that the event reports the latest value. This test goes inside the same describe block:
it('reports the running total on every click', async () => {
const element = createElement('c-counter', { is: Counter });
element.step = 2;
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('countchange', handler);
const button = element.shadowRoot.querySelector('button');
button.click();
button.click();
await Promise.resolve();
expect(handler).toHaveBeenCalledTimes(2);
expect(handler.mock.calls.map((call) => call[0].detail.count)).toEqual([2, 4]);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('4');
});Mapping over mock.calls checks the whole series of values in one assertion. A failure message then shows the full list instead of a single wrong number.
Simulate typing and other events
Only a few DOM methods, such as click() and focus(), fire an event by themselves. For anything else, set the state the user would have produced and dispatch the event yourself. Take a searchBox component that sends a trimmed search term when its input changes.
<template>
<input type="text" class="term" onchange={handleChange} />
</template>import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
handleChange(event) {
this.dispatchEvent(
new CustomEvent('search', {
detail: { term: event.target.value.trim() }
})
);
}
}The test sets value on the input and then dispatches a change event:
import { createElement } from 'lwc';
import SearchBox from 'c/searchBox';
describe('c-search-box', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('fires search with the trimmed term', () => {
const element = createElement('c-search-box', { is: SearchBox });
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('search', handler);
const input = element.shadowRoot.querySelector('input');
input.value = ' acme ';
input.dispatchEvent(new Event('change'));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail).toEqual({ term: 'acme' });
});
});This test has no await. Nothing in the template changes after the event, so there is nothing to wait for.
Use the event type that matches the handler. A component bound to onkeyup needs new KeyboardEvent('keyup', { key: 'Enter' }). A component bound to oninput needs new Event('input'). Dispatching the wrong type is a common reason for a handler that never runs.
Check event options
A CustomEvent created without options does not bubble and is not composed. Parents can hear it only when they listen on the exact element that dispatched it. Whether you want that depends on the design.
| Option | Default | Effect when `true` |
|---|---|---|
| `bubbles` | `false` | The event travels up through the ancestors of the dispatching element. |
| `composed` | `false` | The event also crosses shadow DOM boundaries. |
| `cancelable` | `false` | A listener can call `preventDefault()`, and `dispatchEvent` returns `false`. |
If a component sets any of these options, test them. This is how you would check the flags on the first call in the counter test:
const event = handler.mock.calls[0][0];
expect(event.bubbles).toBe(false);
expect(event.composed).toBe(false);Common errors
- Listener added after the action. Register
addEventListenerbefore you callclick(). An event that has already fired is not replayed. - Missing
awaitbefore DOM assertions. The test then reads the old DOM. Because the failure message shows the stale text, it looks like a logic bug in the component. - Querying the wrong root.
document.querySelector('button')finds nothing, because the button lives inside the shadow root. Useelement.shadowRoot.querySelector. - Asserting on
calls[0]instead ofcalls[0][0].calls[0]is the argument array, not the event. - Skipping cleanup. Without the
afterEachthat removes elements, an earlier test's component can still be in the document and can affect later tests.
Exercise
A component dispatches new CustomEvent('select', { detail: { id: '001' } }) when a list item is clicked. A test calls item.click(), then asserts expect(handler.mock.calls[0].detail.id).toBe('001'), and the test fails. What is wrong, and what is the fix?
Show answer
handler.mock.calls[0] is the array of arguments for the first call, so it has no detail property. The event object is its first element. The fix is handler.mock.calls[0][0].detail.id. The await Promise.resolve() is only needed if the test also checks re-rendered DOM.
Exercise
Write the line that makes a test input fire the same event as a user pressing Enter, for a component with onkeyup={handleKeyUp} on the input. Assume input is already queried.
Show answer
input.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }));