Sub topic 10
Testing error and empty-data paths
This chapter assumes you can write a basic LWC Jest test with createElement, and that you know @wire, imported Apex methods, and async/await. The earlier chapters showed the success path. Here you cover the two other outcomes a data source can produce: an error and an empty result.
Why the unhappy paths need their own tests
A component that reads data has at least four states: loading, data, empty, and error. A success-only test leaves the other three unchecked. These states are also where users see broken screens, such as a blank area where a message should be.
| Path | What the data source returns | What the component should show |
|---|---|---|
| Success | A non-empty array | One list item per record |
| Empty | An empty array | A "no results" message |
| Error | An error object | An error message |
Each path becomes one test. The tests use the same setup, and only the mocked value changes.
Errors from a wired Apex method
A test wire adapter has an error function. It sends an error to the wired property, so the component takes its error branch.
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));
describe('c-contact-list error and empty paths', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders an error message when the wire errors', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.error();
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
it('renders no list items when the wire emits an empty array', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.emit([]);
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});
});The error test checks two things. The error element must exist, and no list items may appear. The empty test checks the reverse: no items and no error. An empty result is not a failure, so the component must not show an error for it.
Errors from an imperative Apex call
An imperative call returns a promise. Use mockRejectedValue to make it reject. Apex errors reach the component as an object with a body.message property, so the mock should have that shape.
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));
describe('c-contact-search error and empty paths', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows an error when Apex rejects', async () => {
findContacts.mockRejectedValue({ body: { message: 'Server error' } });
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
});
it('shows no items when Apex resolves with an empty array', async () => {
findContacts.mockResolvedValue([]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});
});Set the mock value before you trigger the action. The component calls the mock when the button is clicked, so a value set afterward is too late.
The flow of an error through the test
Checking the branch you meant to reach
A test can pass for the wrong reason. If .error is missing from the template, not.toBeNull() fails, which is correct. But if you only assert that no list items exist, the test passes in the loading state as well. Pair the absence of one element with the presence of another, as the tests above do.
Also check the text when it matters. The component may show error.body.message, so the test can assert that 'Server error' appears in the error element's textContent.
Common mistakes
- Calling
getContactList.error()before the component is attached. Attach the element first, then send the error. - Mocking
mockRejectedValue('Server error')with a plain string. Real Apex errors have abody, so the component may readundefinedand throw. - Skipping
await flushPromises(). The DOM has not updated yet, so the assertion sees the old state.
Exercise
A component renders a "No contacts found" paragraph with class empty when a wired Apex method returns an empty array. Which test-adapter call drives that state, and what should the test assert besides the paragraph?
Show answer
Call getContactList.emit([]) after attaching the element, then await flushPromises(). Assert that .empty is not null. Also assert that no li elements exist and that .error is null, so the test shows the component chose the empty branch and not the error branch.
Exercise
An imperative test uses findContacts.mockRejectedValue('Server error') and the component crashes reading error.body.message. What is wrong and how do you fix it?
Show answer
The mock rejects with a string, but Apex errors are objects with a body property. Reject with { body: { message: 'Server error' } } so the mock matches the real error shape.