Sub topic 13
Testing a component that uses refreshApex
This chapter assumes you can write Jest tests for LWC with @salesforce/sfdx-lwc-jest. It also assumes you have read the earlier chapters on saving a change and then refreshing. The goal is to test your own logic. That means checking that the component calls refreshApex with the right object, at the right time, and handles failure. A Jest test cannot show that the server returned fresh records.
What to test and what to skip
Jest runs without a server, so the cache and the Apex call are both replaced.
| Check | Worth testing |
|---|---|
| `updateEmail` is called with the values from the event | Yes |
| `refreshApex` is called once after a successful save | Yes |
| `refreshApex` receives the wired result object | Yes |
| `refreshApex` is not called when the save fails | Yes |
| The refreshed records are actually newer | No. This needs a sandbox or an end-to-end test. |
Setting up the mocks
Three things need mocking: the wired Apex method, the imperative method, and refreshApex.
The wired method gets a test wire adapter. Its emit function pushes data into the component as if the server had sent it. The other two are plain jest.fn() mocks.
The tests below use the property-wire component, ContactListSimple. Assume its template wraps the list in <div class="list" onsave={handleSave}>. The test can then dispatch a save event on that element.
import { createElement } from 'lwc';
import ContactListSimple from 'c/contactListSimple';
import { refreshApex } from '@salesforce/apex';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
import getContacts from '@salesforce/apex/ContactController.getContacts';
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 MOCK_CONTACTS = [
{ Id: '003000000000001AAA', Name: 'Ada Lovelace', Email: '[email protected]' }
];
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function createComponent() {
const element = createElement('c-contact-list-simple', {
is: ContactListSimple
});
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
function fireSave(element) {
const list = element.shadowRoot.querySelector('.list');
list.dispatchEvent(
new CustomEvent('save', {
detail: {
contactId: '003000000000001AAA',
email: '[email protected]'
}
})
);
}
describe('c-contact-list-simple', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('refreshes the wire after a successful save', async () => {
updateEmail.mockResolvedValue();
const element = createComponent();
getContacts.emit(MOCK_CONTACTS);
await flushPromises();
fireSave(element);
await flushPromises();
expect(updateEmail).toHaveBeenCalledWith({
contactId: '003000000000001AAA',
email: '[email protected]'
});
expect(refreshApex).toHaveBeenCalledTimes(1);
expect(refreshApex).toHaveBeenCalledWith(
expect.objectContaining({ data: MOCK_CONTACTS })
);
});
it('does not refresh when the save fails', async () => {
updateEmail.mockRejectedValue(new Error('Save failed'));
const element = createComponent();
getContacts.emit(MOCK_CONTACTS);
await flushPromises();
fireSave(element);
await flushPromises();
expect(refreshApex).not.toHaveBeenCalled();
});
});How the tests work
The first test emits data before saving, so the wired property holds a real { data, error } object. The assertion expect.objectContaining({ data: MOCK_CONTACTS }) proves that the component passed the wired result and not this.contacts.data. This catches the first mistake from the pitfalls chapter.
The second test relies on await updateEmail(...) throwing before the refreshApex line runs. In the property-wire component, that rejection is not caught. The event handler returns a rejected promise, and the test still passes because it only checks that refreshApex was never called. If your component catches the error, as ContactList does, you can also assert on the error state it shows.
flushPromises waits for the chain of await calls in handleSave to finish. Without it, the assertions run too early and fail even though the code is correct.
Testing the function-wire version
For ContactList, the stored object is wiredContactsResult. The same test applies. Emit data, fire the save, and assert that refreshApex was called with expect.objectContaining({ data: MOCK_CONTACTS }). If you forget to store result in the wire function, this assertion fails, which is the check you want.
Exercise
A test asserts expect(refreshApex).toHaveBeenCalled() and passes. The component actually calls refreshApex(this.contacts.data). What assertion would catch the bug?
Show answer
Assert on the argument, for example expect(refreshApex).toHaveBeenCalledWith(expect.objectContaining({ data: MOCK_CONTACTS })). Passing the bare array fails this check, because an array has no data property. toHaveBeenCalled() only proves the function ran, not that it got the wired result.