Sub topic 6
Wait for re-rendering before asserting
This chapter assumes you can write a basic Jest test that renders a component with createElement and finds elements through shadowRoot. It also assumes you are comfortable with promises and async/await. The counter component from the setup chapter is used again here.
Why the DOM is stale right after a change
A Lightning web component does not rewrite its DOM the moment a field changes. When a reactive field or a public property changes, the framework marks the component as dirty. It then schedules one re-render as a microtask. A microtask is a small job that the JavaScript engine runs after the current synchronous code finishes and before it handles timers or other events. Several changes made in the same synchronous block therefore produce a single re-render.
In a browser you rarely notice this. In a test it matters, because your test code is also running synchronously. If you change state and read the DOM on the next line, the re-render has not happened yet. The assertion sees the old DOM.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the new count after a click (fails)', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
const count = element.shadowRoot.querySelector('.count');
expect(count.textContent).toBe('1');
});
});This test fails with Expected: "1" and Received: "0". The click handler ran synchronously and count is now 1 in the component class. The template has not been re-evaluated yet.
The standard fix: await one microtask
Make the test function async and wait for a resolved promise before asserting.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the new count after a click', async () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const count = () => element.shadowRoot.querySelector('.count');
expect(count().textContent).toBe('0');
element.shadowRoot.querySelector('button').click();
expect(count().textContent).toBe('0');
await Promise.resolve();
expect(count().textContent).toBe('1');
});
});The test checks the stale value on purpose, to show the sequence. You do not need that check in your own tests.
Why `await Promise.resolve()` is enough
The click handler changes count, and the framework queues its re-render microtask during that change. After that, await Promise.resolve() queues the continuation of your test function. Microtasks run in the order they were queued, so the re-render runs first. When your test resumes, the DOM is up to date.
This depends on order. The wait only works if the change that triggers the re-render happened before the await.
Which changes need a wait
| Action in the test | Is a wait needed before reading the DOM? |
|---|---|
| `appendChild(element)` for the first time | No. The first render happens synchronously. |
| Setting a public property before `appendChild` | No. The value is used for the first render. |
| Setting a public property after `appendChild` | Yes. |
| Calling `.click()` or dispatching an event that changes state | Yes. |
| Calling a public `@api` method that changes state | Yes. |
| Resolving a mocked Apex promise or emitting wire data | Yes, and often more than one microtask. |
Here is a property change after the component is attached. The component is a small greeting.
<template>
<p class="greeting">Hello, {name}</p>
</template>import { LightningElement, api } from 'lwc';
export default class Greeting extends LightningElement {
@api name = 'World';
}import { createElement } from 'lwc';
import Greeting from 'c/greeting';
describe('c-greeting', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('re-renders when the name changes', async () => {
const element = createElement('c-greeting', { is: Greeting });
document.body.appendChild(element);
const text = () =>
element.shadowRoot.querySelector('.greeting').textContent;
expect(text()).toBe('Hello, World');
element.name = 'Ada';
await Promise.resolve();
expect(text()).toBe('Hello, Ada');
});
});The text function queries the DOM each time it is called. Querying again after a wait is safer than holding on to an element reference. A re-render can replace elements, for example when an lwc:if block flips or a list changes.
When one microtask is not enough
The single await Promise.resolve() covers only changes that trigger a re-render directly. Some chains need more time.
- Mocked promises. A component that calls
getContacts().then(...)updates its state in thethencallback. That callback runs in a later microtask, and the re-render is queued after it. One awaited microtask in the test is too early. - Parent and child components. A change in a parent can re-render a child, and the child's own reactive changes can queue another render.
- Timers. If the component uses
setTimeout, you must either wait for the timer or control it with Jest fake timers.
For promise chains, a common helper waits for a macrotask. A macrotask is a full turn of the event loop, such as a setTimeout callback. All pending microtasks, including chained promise callbacks and the re-renders they queue, finish before it runs.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));Use it the same way:
getContacts.mockResolvedValue([{ Id: '003000000000001AAA', Name: 'Ada Lovelace' }]);
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(element.shadowRoot.textContent).toContain('Ada Lovelace');Start with await Promise.resolve(). Move to flushPromises only when the component has a promise chain or a nested render that needs it. A test that always waits for a macrotask works, but it can hide the fact that you do not know why the wait is needed.
Common errors
- Forgetting
async.awaitinside a non-async function is a syntax error. Addasyncto the callback passed toit. - Forgetting
await. WritingPromise.resolve();withoutawaitdoes nothing. The assertion runs immediately and sees the stale DOM. - Not returning a promise from the test. If you use
.then()instead ofawait, you must return the promise. Otherwise Jest finishes the test before the assertions run, and a failingexpectis never reported. The test passes when it should fail. - Asserting an old element reference. If you saved
const count = element.shadowRoot.querySelector('.count')before a conditional block changed, that node may no longer be in the DOM. Query again after the wait. - Using
flushPromiseswith fake timers. Afterjest.useFakeTimers(),setTimeoutdoes not fire by itself, soawait flushPromises()never resolves and the test times out. Either use real timers for that test or advance the timers explicitly. - Waiting before the trigger. An
awaitplaced before the click or property change waits for nothing. Wait after the change.
A habit that keeps tests readable
Group each test into three steps: arrange, act, then wait and assert. Put the single await between the act and the assertions, so a reader can see where the DOM is allowed to change.
// arrange
const element = createElement('c-counter', { is: Counter });
element.step = 3;
document.body.appendChild(element);
// act
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
// assert
expect(element.shadowRoot.querySelector('.count').textContent).toBe('3');Exercise
A test clicks a button, then runs expect(element.shadowRoot.querySelector('.count').textContent).toBe('1') on the next line, and it fails with "0". The component class is correct. What is the cause, and what is the smallest change that fixes the test?
Show answer
The click handler changed the reactive field, but the re-render is queued as a microtask and has not run when the assertion executes, so the DOM still shows the old value. Make the test function async and add await Promise.resolve(); between the click and the assertion.
Exercise
A component calls an imperative Apex method in connectedCallback and renders the result in a then callback. The Apex method is mocked with mockResolvedValue. After appendChild, the test uses await Promise.resolve() and the assertion still sees no data. Why, and what do you use instead?
Show answer
The mocked promise resolves in a microtask, the then callback runs in a later microtask, and the re-render is queued after that. One awaited microtask is too early. Wait for a full event loop turn with await new Promise((resolve) => setTimeout(resolve, 0)), usually written as a flushPromises helper, so all chained microtasks and the re-render finish first.
Exercise
Which of these needs a wait before asserting on the DOM? (a) the first appendChild of a component, (b) setting element.name after the component is attached, (c) setting element.name before appendChild.
Show answer
Only (b). The first render happens synchronously during appendChild, and a property set before attaching is used by that first render. A property set after attaching schedules a re-render microtask, so the test must await before asserting.