Sub topic 9
Test user interaction and custom events
This chapter assumes you can render a component with createElement, query its shadow root, and wait for re-rendering with await Promise.resolve(). It also assumes you know how a component dispatches a CustomEvent. Here you will simulate user actions and check the events a component sends to its parent.
What to verify
A component talks to the outside world in two ways. It reacts to user input such as clicks, and it dispatches custom events. A unit test covers both:
- Trigger the interaction on a real element in the shadow DOM.
- Wait for re-rendering.
- Assert on the updated DOM and on the events your listener received.
The counter component used here has a public step property, a count field, and a button that dispatches countchange.
<template>
<p class="count">{count}</p>
<button onclick={handleClick}>Add</button>
</template>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
Find the button in the shadow root and call its click() method. This runs the same onclick handler a user would trigger. Calling handleClick directly is not possible, because the method is not public, and it would skip the template wiring you want to test.
Listen for the custom event
Events dispatched with this.dispatchEvent fire on the host element. Attach a listener to the element returned by createElement, before you trigger the interaction. A jest.fn() mock records every call and the event object it received.
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);
});
});The sequence is shown below.
Read the event payload
handler.mock.calls is an array with one entry per call. Each entry is the list of arguments, so mock.calls[0][0] is the event from the first call. Its detail property holds your payload. Check toHaveBeenCalledTimes first, so a missing event fails with a clear message instead of an error about undefined.
Common errors
- Listener added too late. Events fire synchronously during
click(). Add the listener before clicking. - Missing await. The event fires immediately, but the DOM text updates after re-rendering. Asserting on the DOM without
await Promise.resolve()sees the old value. - Wrong target. A child component's event must be listened for on that child. A parent's handler only sees what bubbles to it. Set
bubbles: trueandcomposed: truein the component if the event must cross shadow boundaries, and test that behavior too. - Leaking state. Without the
afterEachcleanup, elements from earlier tests stay indocument.body.
Other interactions
Inputs work the same way. Set the element's value, then dispatch an event with element.dispatchEvent(new CustomEvent('change')). Use the event type your template listens for.
Exercise
In the counter test, why is the listener attached with element.addEventListener before calling button.click(), and why is the DOM assertion placed after await Promise.resolve() while the handler assertion would also pass without it?
Show answer
click() runs handleClick synchronously, and dispatchEvent calls listeners immediately, so a listener added afterward would miss the event. That is why the handler assertions pass without the await. The rendered text only updates in a microtask after the field changes, so the DOM assertion needs await Promise.resolve() first.
Exercise
Write the assertion that checks the second countchange event reported a count of 4 when step is 2 and the button was clicked twice.
Show answer
expect(handler.mock.calls[1][0].detail.count).toBe(4);