Sub topic 2
Wait for re-rendering before asserting
This chapter assumes you know LWC templates, @api properties, events, promises, and async/await. LWC rendering is asynchronous. After a property change or user action, the DOM may still contain the old output when your test continues.
Wait for re-rendering before asserting
Wait for the next microtask before querying updated DOM. A microtask is work JavaScript schedules to run after the current synchronous code finishes.
import { createElement } from 'lwc';
import Counter from 'c/counter';
const flushPromises = () => Promise.resolve();
it('renders the new count after a click', async () => {
const element = createElement('c-counter', { is: Counter });
element.step = 2;
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
await flushPromises();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('2');
});The same rule applies after setting a public property. Set the property, wait, and then assert on rendered output.
Clean up between tests
Each test needs a fresh component. Remove every element appended to document.body, and clear mocks when tests share mock functions.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});Without cleanup, elements and event listeners from one test can affect another test. This creates order-dependent failures.
Test public properties and methods
A public property is an @api value that a parent can set. Assign it before attaching the component when the initial render depends on it. To test an @api method, call the method through the component element, wait for any resulting render, and assert on the public behavior rather than private fields.
Test user interaction and custom events
Attach an event listener before triggering the action. Then wait for rendering and inspect the event mock.
const handler = jest.fn();
element.addEventListener('countchange', handler);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.count).toBe(2);Exercise
Why should a test wait after clicking an LWC button?
Show answer
The click can change reactive state and dispatch an event before the component finishes rendering. Waiting lets the test observe the updated DOM.