Sub topic 13
Testing a Component That Uses refreshApex
What this chapter covers
This chapter assumes you can write a Jest test for an LWC with createElement. It also assumes you know the ContactList component from earlier in the tutorial, which wires getContacts to a function, saves with updateEmail, and then calls refreshApex on the stored wire result.
A Jest test cannot reach a real org or the real client-side cache, so it can't prove that refreshApex fetches fresh records. A Jest test can prove that your component:
- passes the correct object to
refreshApex - calls
refreshApexonly after the save succeeds - skips the refresh when the save fails
- shows an error when the save or the refresh fails
- re-renders when the wire provisions new data
Those are the mistakes that make a refresh silently do nothing, so they are worth testing.
What you mock and why
Three things in this component talk to the platform. Each needs a stand-in.
| Dependency | Stand-in | Reason |
|---|---|---|
| `getContacts` (wired Apex) | Test wire adapter from `createApexTestWireAdapter` | Lets the test push data or an error into the wire with `emit()` and `error()` |
| `updateEmail` (imperative Apex) | `jest.fn()` | Lets the test choose whether the save resolves or rejects |
| `refreshApex` | `jest.fn()` that returns a resolved promise | Lets the test inspect the argument and the call order |
The Apex wire adapter delivers the same { data, error } shape the real wire provisions. That shape matters here, because the component stores it and later hands it to refreshApex.
Supporting files
The component needs a template that the test can interact with. This one renders a child element for each contact and listens for its save event. It also shows an error paragraph.
<template>
<template lwc:if={contacts}>
<template for:each={contacts} for:item="contact">
<c-contact-editor
key={contact.Id}
data-id={contact.Id}
onsave={handleSave}
></c-contact-editor>
</template>
</template>
<p lwc:if={error} class="error">Could not load or save contacts.</p>
</template>The template needs two small changes to work with the component class from earlier in the tutorial. The class must expose contacts and error as tracked fields, which it already does because class fields are reactive. It must also keep handleSave as shown, with the try/catch around both awaits.
In a real project c-contact-editor is a real component with an input and a Save button. In the test it only needs to exist and to be the target of a dispatched event. A stub is enough:
// force-app/main/default/lwc/contactEditor/contactEditor.js
import { LightningElement } from 'lwc';
export default class ContactEditor extends LightningElement {}<!-- force-app/main/default/lwc/contactEditor/contactEditor.html -->
<template></template>The test file
Save this as force-app/main/default/lwc/contactList/__tests__/contactList.test.js.
import { createElement } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import ContactList from 'c/contactList';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
jest.mock(
'@salesforce/apex/ContactController.updateEmail',
() => ({ default: jest.fn() }),
{ virtual: true }
);
jest.mock(
'@salesforce/apex',
() => ({ refreshApex: jest.fn(() => Promise.resolve()) }),
{ virtual: true }
);
const CONTACTS = [
{ Id: '003000000000001AAA', Name: 'Ada Lovelace', Email: '[email protected]' },
{ Id: '003000000000002AAA', Name: 'Grace Hopper', Email: '[email protected]' }
];
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function createComponent() {
const element = createElement('c-contact-list', { is: ContactList });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
function dispatchSave(element, detail) {
const editor = element.shadowRoot.querySelector('c-contact-editor');
editor.dispatchEvent(new CustomEvent('save', { detail }));
}
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('passes the whole wired result to refreshApex after a successful save', async () => {
updateEmail.mockResolvedValue();
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
dispatchSave(element, { contactId: CONTACTS[0].Id, email: '[email protected]' });
await flushPromises();
expect(updateEmail).toHaveBeenCalledWith({
contactId: CONTACTS[0].Id,
email: '[email protected]'
});
expect(refreshApex).toHaveBeenCalledTimes(1);
const argument = refreshApex.mock.calls[0][0];
expect(argument).toHaveProperty('data');
expect(argument.data).toEqual(CONTACTS);
});
it('refreshes only after the save has finished', async () => {
updateEmail.mockResolvedValue();
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
dispatchSave(element, { contactId: CONTACTS[0].Id, email: '[email protected]' });
await flushPromises();
const saveOrder = updateEmail.mock.invocationCallOrder[0];
const refreshOrder = refreshApex.mock.invocationCallOrder[0];
expect(saveOrder).toBeLessThan(refreshOrder);
});
it('does not refresh and shows an error when the save fails', async () => {
updateEmail.mockRejectedValue({ body: { message: 'Save failed' } });
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
dispatchSave(element, { contactId: CONTACTS[0].Id, email: 'bad' });
await flushPromises();
expect(refreshApex).not.toHaveBeenCalled();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
});
it('shows an error when the refresh fails', async () => {
updateEmail.mockResolvedValue();
refreshApex.mockRejectedValueOnce(new Error('Refresh failed'));
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
dispatchSave(element, { contactId: CONTACTS[0].Id, email: '[email protected]' });
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
});
it('re-renders when the wire provisions new data', async () => {
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
expect(element.shadowRoot.querySelectorAll('c-contact-editor')).toHaveLength(2);
getContacts.emit([CONTACTS[0]]);
await flushPromises();
expect(element.shadowRoot.querySelectorAll('c-contact-editor')).toHaveLength(1);
});
});Run it with npx sfdx-lwc-jest -- --watch or your project's npm run test:unit script.
How each test works
Argument check
The first test guards against the most common pitfall, which is passing this.contacts.data or a copied object instead of the wired result. The assertion reads the argument that the component actually gave to the mock. It checks that the argument has a data property that holds the contacts. If someone changes the code to refreshApex(this.wiredContactsResult.data), the argument becomes an array. The toHaveProperty('data') check then fails.
This test checks the shape of the argument, not its identity. The component stores whatever the wire provisioned, and the adapter decides how to wrap your emit() value. Asserting on the shape keeps the test independent of that detail.
Call order
jest.fn() records an invocationCallOrder number for every call, and the numbers increase across all mocks in a test file. Comparing the two numbers proves that the save started before the refresh. It also catches a missing await, such as updateEmail(...) without await followed by refreshApex(...). In that case the refresh would fire before the save completes and re-fetch the old data.
Order alone does not prove the component waited for the save to resolve. To prove that, make the save a promise you control and check that the refresh has not run yet:
it('waits for the save promise before refreshing', async () => {
let finishSave;
updateEmail.mockReturnValue(new Promise((resolve) => { finishSave = resolve; }));
const element = createComponent();
getContacts.emit(CONTACTS);
await flushPromises();
dispatchSave(element, { contactId: CONTACTS[0].Id, email: '[email protected]' });
await flushPromises();
expect(refreshApex).not.toHaveBeenCalled();
finishSave();
await flushPromises();
expect(refreshApex).toHaveBeenCalledTimes(1);
});Failure paths
The third and fourth tests cover the two failure points. When updateEmail rejects, the catch block runs and refreshApex never executes. This test fails if someone moves the refresh into a finally block. When refreshApex rejects, the save has already succeeded, but the user still needs to see the problem. Use mockRejectedValueOnce so the rejection does not leak into later tests.
Re-rendering
The last test simulates the result of a successful refresh. In production, refreshApex makes the wire provision a new value. In the test you do the same by calling getContacts.emit() again. If the component keeps showing the old list, the handler in the wired function is not updating this.contacts.
Mistakes in test setup
- Path mismatch in
jest.mock. The string must match the import exactly, for example@salesforce/apex/ContactController.getContacts. A typo leaves the real stub in place, andemitis then undefined. - Too few awaited ticks. The component awaits two promises in a row. A single
await Promise.resolve()is not enough. UseflushPromisesso the whole chain finishes before you assert. - Mock state leaking between tests. Call
jest.clearAllMocks()inafterEach. OtherwisetoHaveBeenCalledTimes(1)fails on the second test. Note thatclearAllMockskeeps implementations set withmockResolvedValue, so set the one you need at the start of each test. - Skipping
emitbefore the action. If the wire has not emitted,wiredContactsResultis undefined and the component passesundefinedtorefreshApex. Always emit first. - Missing child stub. If
c/contactEditordoes not exist, the template fails to compile in Jest.
Testing the Apex side
The Apex controller from the first chapter needs its own Apex tests. Insert a Contact, call getContacts, and assert the result. Then call updateEmail as a user with and without field access. The WITH USER_MODE and update as user clauses make permission failures part of the behavior, so test them with System.runAs. Jest never exercises that code.
Exercise
A teammate changes handleSave to call refreshApex(this.wiredContactsResult.data). Which test in this chapter fails, and what assertion catches it?
Show answer
The first test, "passes the whole wired result to refreshApex after a successful save." The argument is now the contacts array, so expect(argument).toHaveProperty('data') fails. The array has no data property, and the real refresh would do nothing for the same reason.
Exercise
You remove the await in front of updateEmail(...) in handleSave. The "refreshes only after the save has finished" test still passes. Why, and which test would catch the change?
Show answer
With the mock mockResolvedValue(), updateEmail is called before refreshApex even without await, so the call-order comparison still holds. The "waits for the save promise before refreshing" test catches it. The save promise stays pending, but the refresh runs immediately, so expect(refreshApex).not.toHaveBeenCalled() fails.
Exercise
Write the assertion that checks the component shows no error after a fully successful save and refresh.
Show answer
After await flushPromises(), add expect(element.shadowRoot.querySelector('.error')).toBeNull();. This works because the template renders the error paragraph only when error is set.