Sub topic 4
Waiting for rendering: flushing promises
This chapter assumes you can write a basic Jest test for an LWC component with createElement. It also assumes you know what a promise is and how async/await works. It explains why a test that looks correct can fail because the DOM has not updated yet, and how to wait for the update.
Why the DOM lags behind your code
LWC does not re-render a component the moment a field changes. When a reactive field changes, the framework schedules one re-render as a microtask. A microtask is a small job that the JavaScript engine runs as soon as the current synchronous code finishes, before it moves on to timers or I/O. Several field changes in the same synchronous block cause a single re-render.
A test is ordinary synchronous code until its first await. So if a test triggers a change and checks the DOM on the next line, the re-render has not run yet. The assertion sees the old DOM.
The following component shows the effect.
// clickCounter.js
import { LightningElement } from 'lwc';
export default class ClickCounter extends LightningElement {
count = 0;
handleClick() {
this.count += 1;
}
}<!-- clickCounter.html -->
<template>
<button onclick={handleClick}>Add</button>
<p>{count}</p>
</template>The test below checks the paragraph before and after yielding to the microtask queue.
import { createElement } from 'lwc';
import ClickCounter from 'c/clickCounter';
describe('c-click-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('updates the DOM only after the re-render microtask', async () => {
const element = createElement('c-click-counter', { is: ClickCounter });
document.body.appendChild(element);
const paragraph = element.shadowRoot.querySelector('p');
element.shadowRoot.querySelector('button').click();
// The handler has run, but the template has not re-rendered.
expect(paragraph.textContent).toBe('0');
await Promise.resolve();
expect(paragraph.textContent).toBe('1');
});
});await Promise.resolve() pauses the test and puts its continuation at the back of the microtask queue. The re-render was queued earlier, so it runs first.
The two common ways to wait
Test code in LWC projects uses two waiting styles.
await Promise.resolve()yields for one round of microtasks.await flushPromises()yields to the macrotask queue, which runs after all queued microtasks, including chained ones.
The usual definition of flushPromises is:
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));A macrotask is a job such as a timer callback. The engine runs one macrotask, then drains the whole microtask queue, then takes the next macrotask. When the setTimeout callback runs, every promise callback and every re-render that was already pending has finished. That is why the helper is called "flush".
| Approach | What it waits for | Use it when |
|---|---|---|
| `await Promise.resolve()` | One microtask turn | A synchronous event handler or a single `emit` changes a field and you only need the re-render |
| `await flushPromises()` | All pending microtasks, including chains | The component awaits a mocked Apex call, or a promise handler triggers more promises |
When in doubt, use flushPromises. It costs one timer tick and removes guesswork about how many microtask turns the component needs.
Why one `await Promise.resolve()` is sometimes not enough
Every .then callback and every await continuation in your component adds a microtask turn. Consider an imperative Apex call in a component:
// contactSearch.js (excerpt)
async handleSearch() {
this.loading = true;
try {
this.contacts = await findContacts({ searchTerm: this.term });
} catch (e) {
this.error = e.body.message;
} finally {
this.loading = false;
}
}With findContacts.mockResolvedValue([...]) the sequence is:
- The handler sets
loading, then calls the mock and suspends atawait. - The mock's promise is already resolved, so the continuation is queued as a microtask.
- The continuation sets
contacts, runsfinally, and setsloadingtofalse. - A re-render is queued as another microtask.
A test that waits only one turn may run its assertions between step 3 and step 4, or even before step 3. The number of turns depends on how the code is written. Refactoring the component from .then to async/await can change it. A macrotask wait is not tied to those details.
Flushing after wire emits
Wire adapters follow the same rule. When a test calls emit on a test wire adapter, the component's wired property or function receives the value synchronously. The template still updates in a microtask, so you wait before asserting. This example reuses the getRecord stub from sfdx-lwc-jest:
import { createElement } from 'lwc';
import RecordName from 'c/recordName';
import { getRecord } from 'lightning/uiRecordApi';
const mockRecord = {
apiName: 'Account',
id: '001000000000001AAA',
fields: { Name: { value: 'Acme', displayValue: null } }
};
it('shows the account name from getRecord', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
getRecord.emit(mockRecord);
await Promise.resolve();
expect(element.shadowRoot.querySelector('p').textContent).toBe('Acme');
});One microtask turn is enough here because nothing in the chain is asynchronous. The data arrives, the field changes, and the re-render is queued. If the component computes something from the wired data inside a promise, switch to flushPromises.
Observing the loading state
A test that always flushes everything only sees the final state. To check an intermediate state such as a spinner, hold the mocked promise open yourself, assert, then release it.
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
import findContacts from '@salesforce/apex/ContactController.findContacts';
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-search loading state', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows a spinner while Apex is pending, then the results', async () => {
let resolveApex;
findContacts.mockReturnValue(
new Promise((resolve) => {
resolveApex = resolve;
})
);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
// Apex has not answered yet.
expect(element.shadowRoot.querySelector('lightning-spinner')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
resolveApex([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();
expect(element.shadowRoot.querySelector('lightning-spinner')).toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});
});This test assumes the component renders a lightning-spinner while loading is true and an li for each contact. The first flushPromises lets the click handler run and the spinner render. The promise stays pending because the test never calls resolveApex until it chooses to.
Edge cases and failure modes
Fake timers hang `flushPromises`
If a test calls jest.useFakeTimers(), setTimeout no longer fires on its own. await flushPromises() then never resolves and the test fails with a timeout. Two ways out:
- Use
await Promise.resolve()for simple cases. - Advance the clock yourself with
jest.advanceTimersByTime(0), then await a resolved promise so the microtasks drain.
Use fake timers only in tests that need them, for example a debounced input, and restore real timers with jest.useRealTimers() in afterEach.
Asserting too early gives confusing failures
A failing assertion about missing elements or stale text often means "not rendered yet", not "the code is wrong". Before debugging the component, add a flushPromises call and run the test again. If it passes, the cause was timing.
Elements you queried before the flush can go stale
LWC updates existing DOM nodes in place when it can. When a conditional block such as lwc:if toggles, though, the node is removed and a new one is created. A reference you stored before the flush may point to a detached element. Query again after each flush instead of keeping references across waits.
Child components render on their own schedule
A parent's re-render can queue renders for its children. flushPromises covers these because the whole microtask queue drains before the timer fires. A single await Promise.resolve() may not cover them.
Unawaited async work leaks into the next test
If a test finishes while a promise from the component is still pending, the continuation can run during a later test. The effect may be an error in the wrong test, or a mock called one extra time. End each test that triggers async work with a flush, and reset mocks in afterEach.
A rule of thumb
- Synchronous change followed by a DOM check:
await Promise.resolve()is usually enough. - Anything involving a mocked Apex call or a promise chain:
await flushPromises(). - Intermediate states: hold the promise open yourself, flush, assert, release, flush, assert.
Exercise
A test clicks a button whose handler runs this.contacts = await findContacts(params). The mock uses mockResolvedValue. The test then runs await Promise.resolve() and asserts that one li is rendered, but the assertion intermittently fails after the component is refactored. What is the likely cause, and what is the fix?
Show answer
A single await Promise.resolve() waits for only one microtask turn. The await continuation in the component and the queued re-render need more than one turn, and the count changes with how the component is written. Replace it with await flushPromises(), which waits on a setTimeout macrotask and so runs after all pending microtasks, including the re-render.
Exercise
Your test file calls jest.useFakeTimers() in a beforeEach, and every test that awaits flushPromises() now times out. Why does this happen, and how can you fix it?
Show answer
flushPromises resolves from a setTimeout callback. Fake timers replace setTimeout, so the callback never fires unless you advance the clock. Either call jest.advanceTimersByTime(0) and then await a resolved promise, use await Promise.resolve() where one turn is enough, or use real timers in tests that do not need fake ones and call jest.useRealTimers() in afterEach.