Sub topic 13
Unit testing wired components with Jest
A wired component depends on a server call that Jest cannot make. A unit test has to replace the Apex method and the wire adapter, then feed the component data or an error. This chapter shows how to do that with @salesforce/sfdx-lwc-jest and test the ContactList component from earlier in the tutorial.
This chapter assumes you know the basics of Jest (describe, it, expect, async tests) and have read the earlier chapters on wiring to a property, reactive parameters, and error handling.
What a unit test replaces
In a real org, the @wire decorator asks the platform for data. The platform calls your Apex method, applies caching, and delivers { data, error } to the component. None of that exists in Jest, which runs in Node with a simulated DOM.
The test therefore does three things:
- Replaces the import
@salesforce/apex/ContactController.getContactswith a test wire adapter. - Creates the component and attaches it to the document, which starts the wire.
- Calls
emit()orerror()on the adapter to push a value into the component, then checks the rendered DOM.
The Apex code never runs. Sharing rules and field-level security are tested in Apex tests, not here. Jest checks only that the component handles the shapes it receives.
Set up the test runner
Install the Salesforce Jest runner as a development dependency in your SFDX project:
npm install @salesforce/sfdx-lwc-jest --save-devAdd a script to package.json:
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}Jest looks for test files in a __tests__ folder inside the component's bundle. For the contactList component:
force-app/main/default/lwc/contactList/
├── contactList.html
├── contactList.js
├── contactList.js-meta.xml
└── __tests__/
└── contactList.test.jsThe runner resolves lightning/* and @salesforce/* imports to stubs. That is why a component importing @salesforce/apex/... can load in Node at all. The default stub for an Apex import is a plain function. It is not a wire adapter, so the test must replace it.
Mock the Apex import as a wire adapter
Use jest.mock with { virtual: true } and return a test adapter from createApexTestWireAdapter. The adapter wraps a jest.fn(), so the module's default export works both as a wire adapter and as a callable function.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
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 }
);Three details matter here:
virtual: trueis required because the module path does not exist as a real file. Without it, Jest throws "Cannot find module".- The adapter is created inside the factory with
require. Jest hoistsjest.mockcalls above the imports, so a factory cannot refer to variables imported at the top of the file. - The
getContactsyou import in the test is the same adapter object the component receives. That is how the test reachesemit().
Write the first tests
Define mock data that has the same shape Apex returns, a list of Contact records:
const MOCK_CONTACTS = [
{ Id: '003000000000001AAA', Name: 'Ada Lovelace', Email: '[email protected]' },
{ Id: '003000000000002AAA', Name: 'Grace Hopper', Email: '[email protected]' }
];Then add the tests. The helper flushPromises waits one microtask so the component can re-render after a wire emits.
const flushPromises = () => Promise.resolve();
function createComponent(recordId = '001000000000001AAA') {
const element = createElement('c-contact-list', { is: ContactList });
element.recordId = recordId;
document.body.appendChild(element);
return element;
}
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('renders nothing until data arrives', async () => {
const element = createComponent();
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li')).toHaveLength(0);
expect(element.shadowRoot.querySelector('p')).toBeNull();
});
it('renders one list item per contact', async () => {
const element = createComponent();
getContacts.emit(MOCK_CONTACTS);
await flushPromises();
const items = element.shadowRoot.querySelectorAll('li');
expect(items).toHaveLength(2);
expect(items[0].textContent).toBe('Ada Lovelace');
expect(items[1].textContent).toBe('Grace Hopper');
});
it('shows a message when the wire returns an error', async () => {
const element = createComponent();
getContacts.error();
await flushPromises();
const message = element.shadowRoot.querySelector('p');
expect(message).not.toBeNull();
expect(message.textContent).toBe('Could not load contacts.');
expect(element.shadowRoot.querySelectorAll('li')).toHaveLength(0);
});
it('passes the record id to Apex as accountId', () => {
createComponent('001000000000009AAA');
expect(getContacts.getLastConfig()).toEqual({
accountId: '001000000000009AAA'
});
});
});Run them with npm run test:unit.
Each test checks one behavior of the component:
- Before data: the template renders neither the list nor the error. This confirms
lwc:ifguards work on an undefinedcontacts.data. - Data: after
emit, the list renders. The assertion reads fromelement.shadowRoot, because LWC components use synthetic shadow DOM anddocument.querySelectorcannot see inside them. - Error:
error()makes the adapter provision{ error }, so thelwc:elseifbranch renders. - Config:
getLastConfig()returns the parameters the wire last used, which verifies the$recordIdbinding.
Test reactive parameters
When recordId changes, the wire should request data again with the new accountId. Check that by changing the public property after the component is connected:
it('re-runs the wire when recordId changes', async () => {
const element = createComponent('001000000000001AAA');
expect(getContacts.getLastConfig()).toEqual({
accountId: '001000000000001AAA'
});
element.recordId = '001000000000002AAA';
await flushPromises();
expect(getContacts.getLastConfig()).toEqual({
accountId: '001000000000002AAA'
});
});The await matters. LWC applies reactive changes in a microtask, so reading the config immediately after the assignment can return the old value.
Test a function-based wire
A component that wires to a function, like ContactListFn, uses the same mock. The difference is that the function stores results in its own fields, so you assert on what the template shows from those fields. If that component rendered errorMessage, this test would check it:
it('stores the first error message', async () => {
const element = createElement('c-contact-list-fn', { is: ContactListFn });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
getContacts.error({ message: 'Insufficient access' });
await flushPromises();
expect(element.shadowRoot.querySelector('.error').textContent)
.toBe('Insufficient access');
});This assumes the template renders errorMessage in an element with class error, and that the adapter puts the object you pass in error.body. The component's error.body ? error.body.message : error.message line then finds it. If your template differs, adjust the selector. The point is to test through the DOM, not by reading private fields.
Test imperative calls and refreshApex
Imperative calls need a different mock. The default export is a plain function that returns a promise, so use jest.fn() and control the promise:
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
it('loads contacts on demand', async () => {
getContacts.mockResolvedValue(MOCK_CONTACTS);
// create the component, click the button, flush promises
expect(getContacts).toHaveBeenCalledWith({ accountId: '001000000000001AAA' });
});
it('captures the error body message', async () => {
getContacts.mockRejectedValue({ body: { message: 'Boom' } });
// create the component, click the button, flush promises
});Do not mix the two mocks in one test file for the same Apex method. A file gets one factory per module. Put wired and imperative components in separate test files, or use one component that does both with createApexTestWireAdapter and its own jest.fn() for the call.
To test refreshApex, mock the @salesforce/apex module, with jest.mock('@salesforce/apex', () => ({ refreshApex: jest.fn() }), { virtual: true }). Then call the handler and assert that refreshApex received the value the wire stored:
import { refreshApex } from '@salesforce/apex';
expect(refreshApex).toHaveBeenCalledWith(expectedWiredResult);You are testing that your component passes the right object, not that the platform refreshes the cache.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| "Cannot find module '@salesforce/apex/...'" | Missing `virtual: true` | Add `{ virtual: true }` as the third argument to `jest.mock` |
| `getContacts.emit is not a function` | The mock returns a plain `jest.fn()` | Wrap it with `createApexTestWireAdapter` |
| DOM is empty after `emit` | The test did not wait for re-render | `await Promise.resolve()` before asserting |
| Query returns `null` | Using `document.querySelector` | Query `element.shadowRoot` |
| Tests leak into each other | Elements left in `document.body` | Remove them in `afterEach` |
| Mock factory throws a reference error | Factory uses an out-of-scope variable | Use `require` inside the factory |
What Jest does not cover
Jest cannot tell you that the Apex method is secure, that WITH USER_MODE blocks an unreadable field, or that cacheable=true behaves correctly in the browser cache. Cover those with Apex tests (System.runAs) and a manual check in a scratch org. Keep Jest tests focused on the component's logic: what it passes to the wire, what it renders for data, error, and empty states, and what it does on user actions.
Exercise
A test calls getContacts.emit(MOCK_CONTACTS) and immediately asserts querySelectorAll('li') has length 2, but it finds 0. The component, mock, and mock data are correct. What is wrong, and how do you fix it?
Show answer
The test checks the DOM before LWC has re-rendered. Rendering after a wire emit is applied in a microtask. Make the test async, and add await Promise.resolve() (or a flushPromises helper) between emit and the assertion. Also confirm the query runs on element.shadowRoot, not document.
Exercise
You want to verify that a wire re-runs when recordId changes. Which adapter method do you use to read the parameters the wire last used, and why must the test wait after setting the property?
Show answer
Use getContacts.getLastConfig(). It returns the config object, such as { accountId: '001...' }. The test must await Promise.resolve() after assigning the new recordId, because LWC applies reactive changes asynchronously, so the config updates after a microtask.