Sub topic 10
Testing error and empty-data paths
This chapter assumes you can already create a component with createElement, flush promises, and drive a wired property or an imperative Apex call from a test. If any of that is unfamiliar, review the earlier chapters on test wire adapters and Apex mocks first.
Most bugs in data-driven components are not in the success path. They appear when the server fails, when it returns nothing, or when the component is still waiting. This chapter shows how to test those cases with the mocks you already know.
The states a data-driven component can be in
A component that loads data has at least four states. A complete test file covers each one.
| State | What the component received | What the user should see |
|---|---|---|
| Loading | Nothing yet | A spinner or placeholder |
| Success | A non-empty array | One list item per record |
| Empty | An empty array | A "no records" message |
| Error | An error object | An error message |
Empty and error are different states. An empty array means the call worked and found nothing. An error means the call failed. A component that treats both as "no data" shows the wrong message, and the tests in this chapter catch that.
The component used in the examples
The examples use a c-contact-list component wired to ContactController.getContactList. Its JavaScript is below.
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
contacts;
errorMessage;
loaded = false;
@wire(getContactList)
wiredContacts({ data, error }) {
if (data) {
this.contacts = data;
this.errorMessage = undefined;
this.loaded = true;
} else if (error) {
this.contacts = undefined;
this.errorMessage = error.body ? error.body.message : 'Unknown error';
this.loaded = true;
}
}
get isEmpty() {
return this.loaded && this.contacts && this.contacts.length === 0;
}
get hasContacts() {
return this.contacts && this.contacts.length > 0;
}
}The template renders four mutually exclusive blocks, each with a class the tests can select:
.loadingshows whileloadedis false.- A
ulwith oneliper contact shows whenhasContactsis true. .emptyshows whenisEmptyis true..errorshows whenerrorMessageis set.
Testing the loading state
Before any test adapter emits, the wire has delivered nothing. That makes the loading state the easiest one to test. Attach the component, flush, and assert that the placeholder is there and nothing else is.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContactList from '@salesforce/apex/ContactController.getContactList';
jest.mock(
'@salesforce/apex/ContactController.getContactList',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function mountList() {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
return element;
}
describe('c-contact-list states', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the loading state before the wire emits', async () => {
const element = mountList();
await flushPromises();
expect(element.shadowRoot.querySelector('.loading')).not.toBeNull();
expect(element.shadowRoot.querySelector('.error')).toBeNull();
expect(element.shadowRoot.querySelector('.empty')).toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
});The mountList helper removes the repeated three lines from every test. Later examples in this chapter reuse it, along with the same mock and flushPromises.
Testing the empty path on a wired method
An empty result is a successful emit with an empty array. Do not call error() for this case.
it('shows the empty message when Apex returns no contacts', async () => {
const element = mountList();
getContactList.emit([]);
await flushPromises();
expect(element.shadowRoot.querySelector('.empty')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
expect(element.shadowRoot.querySelector('.error')).toBeNull();
expect(element.shadowRoot.querySelector('.loading')).toBeNull();
});Check the absence of the other states, not only the presence of the expected one. A component with a template bug can show the list and the empty message at the same time, and a test that only looks for .empty would pass.
Testing the error path on a wired method
Call error() on the test adapter to deliver an error to the wired function.
it('shows an error message when the wire errors', async () => {
const element = mountList();
getContactList.error();
await flushPromises();
const error = element.shadowRoot.querySelector('.error');
expect(error).not.toBeNull();
expect(error.textContent).toContain('Unknown error');
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});This test passes because the component falls back to 'Unknown error' when the error has no body. Real Apex errors arrive as { body: { message: '...' } }. The arguments that error() accepts differ between @salesforce/sfdx-lwc-jest versions. Check the typings or documentation of your installed version before relying on a custom error body. If your version does not pass one through, test the message extraction as a separate pure function instead.
Testing the empty and error paths on an imperative call
For imperative Apex, you control the outcome with the mock function. Resolve with [] for empty and reject for an error. The example uses the c-contact-search component from earlier chapters. That component has a lightning-input, a lightning-button, a ul of results, and .error and .empty blocks.
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));
function mountSearch() {
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
return element;
}
function search(element, term) {
const input = element.shadowRoot.querySelector('lightning-input');
input.value = term;
input.dispatchEvent(new CustomEvent('change'));
element.shadowRoot.querySelector('lightning-button').click();
}
describe('c-contact-search error and empty paths', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.resetAllMocks();
});
it('shows the empty message when nothing matches', async () => {
findContacts.mockResolvedValue([]);
const element = mountSearch();
search(element, 'Zzz');
await flushPromises();
expect(element.shadowRoot.querySelector('.empty')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
it('shows the server message when Apex rejects', async () => {
findContacts.mockRejectedValue({ body: { message: 'Server error' } });
const element = mountSearch();
search(element, 'Amy');
await flushPromises();
const error = element.shadowRoot.querySelector('.error');
expect(error).not.toBeNull();
expect(error.textContent).toContain('Server error');
});
});Here jest.resetAllMocks() replaces clearAllMocks(). clearAllMocks clears call history but keeps implementations such as mockResolvedValue. A rejected value set in one test could then leak into the next. resetAllMocks removes the implementation too, so each test must set its own.
Testing recovery after an error
Components often keep stale state. If a search fails and the user searches again successfully, the old error must disappear. This is a common real bug, and it needs two calls in one test. Use mockRejectedValueOnce and mockResolvedValueOnce to script the sequence.
it('clears the error after a successful retry', async () => {
findContacts
.mockRejectedValueOnce({ body: { message: 'Server error' } })
.mockResolvedValueOnce([{ Id: '001', Name: 'Amy Taylor' }]);
const element = mountSearch();
search(element, 'Amy');
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
search(element, 'Amy');
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});The wired equivalent is to call getContactList.error(), flush, call getContactList.emit([...]), and flush again. The test adapter lets you emit repeatedly on the same component, so the same recovery check works there.
Errors your component does not handle
If a component calls Apex with .then() and has no .catch(), a rejected mock produces an unhandled promise rejection. Depending on your Node and Jest versions, this either fails the test with a confusing message or is silently ignored. A silent pass hides the bug. The reliable check is to assert on the visible result. If your test expects an error message and none appears, the test fails at the assertion and points you to the missing handler.
Also note that mockRejectedValue returns a rejected promise. It does not throw synchronously. If your component uses try/catch with await, both forms work. If you need to test a synchronous throw, use mockImplementation(() => { throw new Error('boom'); }). Real Apex calls never throw synchronously, so this form tests code paths that cannot happen in production.
Checklist for each data source
For every wired property or imperative call, write at least these tests:
- Loading: nothing delivered yet.
- Success: at least one record, with the count checked.
- Empty: an empty array, with the success list absent.
- Error: a failure, with the message visible and no list.
- Recovery, where the component can retry or the wire config can change.
Exercise
A test calls getContactList.emit([]) and then asserts only that .empty exists. The component has a template bug that renders the empty message and the loading spinner together. Why does the test pass, and how do you fix it?
Show answer
The test only checks that the expected element is present, so it cannot see extra elements that should not be there. Add assertions that the other states are absent, such as expect(element.shadowRoot.querySelector('.loading')).toBeNull() and expect(element.shadowRoot.querySelector('.error')).toBeNull().
Exercise
An imperative test file uses jest.clearAllMocks() in afterEach. Test 1 sets findContacts.mockRejectedValue(...). Test 2 never sets a mock value but expects an empty result. Test 2 shows an error. What causes this, and what is the fix?
Show answer
clearAllMocks() resets call history but keeps implementations, so the rejected value from test 1 is still active in test 2. Use jest.resetAllMocks() in afterEach for a file that only mocks imperative Apex, and set the value explicitly in each test, for example findContacts.mockResolvedValue([]).
Exercise
Write the two statements that make findContacts reject once and then resolve with one contact, so a test can check that an error message disappears after a retry.
Show answer
findContacts.mockRejectedValueOnce({ body: { message: 'Server error' } }).mockResolvedValueOnce([{ Id: '001', Name: 'Amy Taylor' }]); This chain is one statement. The first call rejects and the second resolves.