Sub topic 6
Wait for re-rendering before asserting
This chapter assumes you can write a basic Jest test with createElement, and that you know promises and async/await. You should also know how to query the shadow root, which earlier chapters covered.
Why assertions fail right after a change
A Lightning web component does not update the DOM the moment a field changes. The framework batches changes and re-renders in a microtask. A microtask is a small job that the JavaScript engine runs after the current synchronous code finishes.
In a test, this means the DOM still shows the old output on the line right after you change a property or click a button. The test must wait for the re-render before it asserts.
Wait one microtask
The counter component from the earlier chapters updates count in a click handler. The test below shows the failure and the fix.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter rendering', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the old value before re-rendering', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
// The handler has run, but the DOM has not been updated yet.
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
it('shows the new value after awaiting', async () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('1');
});
});The first test passes only because it asserts the stale value. Do not write tests like it. It is here to show what the DOM looks like before the re-render.
await Promise.resolve() works because the component's re-render is queued before your continuation. Your code resumes after the render has run.
Setting a public property
The same rule applies when the test changes a public property from outside. Setting element.step marks the component for re-rendering, so await before you assert on anything that depends on it.
it('re-renders when a public property changes', async () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.step = 5;
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('5');
});When one microtask is not enough
A single await Promise.resolve() covers one render. It does not cover work that finishes later, such as:
- A promise from an Apex call or another asynchronous function.
- A child component that renders after the parent re-renders.
- A render that triggers a second change, for example in
renderedCallback.
For these cases, use a helper that waits for all pending promises to settle.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));setTimeout with a delay of 0 runs after every queued microtask, so everything that was pending has finished by then. Use await flushPromises() in place of await Promise.resolve() when the test involves asynchronous work.
| Situation | What to await |
|---|---|
| Click or property change, one render | `await Promise.resolve()` |
| Mocked Apex call resolving | `await flushPromises()` |
| Change that causes a second change | `await flushPromises()` |
Common errors
- Forgetting
async.awaitoutside anasyncfunction is a syntax error. Mark theitcallbackasync. - Forgetting
await. The test finishes before the assertions run, or the assertions see stale DOM. - Re-querying not needed, but stale values are. A reference to an element stays valid if the template keeps the element. If the template adds or removes elements (for example with
if:true), query again after the await. - Using
flushPromiseseverywhere. It works, but it hides which change you are waiting for. Prefer the single microtask when it is enough.
Exercise
A test sets element.step = 3, clicks the button, and immediately asserts that .count shows 3. The assertion fails and reports 0. What is wrong, and what is the smallest fix?
Show answer
The component has not re-rendered yet, because the DOM updates in a microtask after the click handler runs. Mark the test function async and add await Promise.resolve(); between the click and the assertion.
Exercise
A test mocks an Apex method with mockResolvedValue and asserts on the rendered result after only await Promise.resolve(). It fails intermittently. Which helper should replace the single await, and why?
Show answer
Use await flushPromises(), which is new Promise((resolve) => setTimeout(resolve, 0)). The Apex promise and the render that follows take more than one microtask. setTimeout runs after all queued microtasks have finished.