Sub topic 4
Waiting for rendering: flushing promises
This chapter assumes you can write a basic Jest test with describe, it and expect. It also assumes you understand promises and async/await, and that you know how a component is created with createElement and attached to the DOM.
Why the DOM is not ready right away
LWC does not update the DOM at the moment a value changes. When a reactive field changes, the framework queues a re-render and runs it later, in a microtask. Your test code keeps running first. If you assert on the DOM straight after a change, you read the old output.
The same applies to data from a wire adapter or an Apex call. emit() sets the wired value, and the component re-renders only after the current JavaScript task yields.
Here is a small component with a reactive field.
<template>
<button onclick={handleClick}>Add</button>
<p>{count}</p>
</template>import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
count = 0;
handleClick() {
this.count += 1;
}
}This test shows the gap between the change and the render.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('re-renders after a click', async () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
// The re-render has not happened yet.
expect(element.shadowRoot.querySelector('p').textContent).toBe('0');
await Promise.resolve();
expect(element.shadowRoot.querySelector('p').textContent).toBe('1');
});
});await Promise.resolve() yields once, so the queued re-render runs before the next line.
The flushPromises helper
One await Promise.resolve() waits for a single microtask. Real tests often involve a chain: an Apex promise resolves, a .then() handler sets a field, and then the render runs. Each link in that chain adds a microtask, and counting them is fragile.
The standard fix is a helper that waits for a macrotask instead.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));The JavaScript engine drains the whole microtask queue before it starts the next macrotask. A setTimeout callback is a macrotask. By the time it fires, every pending promise callback and re-render has finished, however long the chain was.
The diagram shows the order of events.
Using it with a mocked Apex call
This is how the helper is used with a mocked imperative Apex method, using the same pattern as the later chapters.
it('shows results after Apex resolves', async () => {
findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});Without the await, the assertion would run while the list is still empty, and the test would fail even though the component is correct.
Choosing between the two waits
| Wait | What it covers | Use it when |
|---|---|---|
| `await Promise.resolve()` | One microtask | One reactive change or one `emit()` and a direct render |
| `await flushPromises()` | All pending microtasks and renders | Apex promises, chained handlers, or when unsure |
If a single Promise.resolve() works, it is fine. If you are unsure, use flushPromises(). It costs almost nothing.
Common mistakes
- Forgetting
asyncon the test function, soawaitis a syntax error. - Forgetting to
awaitthe helper. The call returns a promise, and the assertion then runs immediately. - Querying an element before the wait and asserting on it after. Element references usually stay valid, but a re-render can add or remove elements. Query again after the wait.
Exercise
A test mocks an imperative Apex method with mockResolvedValue, clicks a button, and immediately asserts that the list has one item. The assertion fails, but the component works in the browser. What is the likely cause, and how do you fix it?
Show answer
The assertion runs before the Apex promise resolves and before the component re-renders. Add await flushPromises() after the click and before the assertion, so all pending microtasks and the render finish first.