Sub topic 3
Mocking Dependencies in LWC Jest Tests
Assume you know LWC templates, @api properties, events, promises, and basic Jest assertions. These tests isolate the component from Salesforce services and child implementations.
Mock imperative Apex calls
An imperative Apex import is a function in a Jest test. Mock it before the test runs, then control whether it resolves or rejects.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-list', () => {
afterEach(() => {
document.body.replaceChildren();
jest.clearAllMocks();
});
it('renders contacts returned by Apex', async () => {
getContacts.mockResolvedValue([
{ Id: '003000000000001AAA', Name: 'Ada Lovelace' }
]);
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(getContacts).toHaveBeenCalledTimes(1);
expect(element.shadowRoot.textContent).toContain('Ada Lovelace');
});
it('shows an error when Apex rejects', async () => {
getContacts.mockRejectedValue(new Error('Request failed'));
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(element.shadowRoot.textContent).toContain('Request failed');
});
});mockResolvedValue tests success. mockRejectedValue tests the error path. Wait for pending promises before checking rendered output.
Test wired components
Use a test wire adapter to emit data or an error. This tests the component's response without calling Salesforce.
import { registerApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const getContactsAdapter = registerApexTestWireAdapter(getContacts);
it('renders data from a wire', async () => {
getContactsAdapter.emit([{ Id: '1', Name: 'Ada Lovelace' }]);
await Promise.resolve();
expect(element.shadowRoot.textContent).toContain('Ada Lovelace');
});Work with base components and child components
The Jest environment supplies lightweight versions of base Lightning components. Assert the public contract, such as an input value or dispatched event, rather than internal implementation.
For custom child components, query the child element and verify its public properties. Test the child separately.
Mock platform modules, labels, and navigation
Static labels and common platform modules have Jest mocks supplied by sfdx-lwc-jest. Mock navigation when you need to verify a navigation request, and assert the requested page reference instead of inspecting Salesforce internals.
Measure coverage and debug failing tests
Add these scripts to package.json:
{
"scripts": {
"test:unit:coverage": "sfdx-lwc-jest -- --coverage",
"test:unit:debug": "sfdx-lwc-jest -- --runInBand"
}
}Coverage shows untested statements, branches, functions, and lines. A failing assertion usually means the component state is wrong, the test queried too early, or a dependency was not mocked.
Exercise
Which mock should you use to test an imperative Apex error?
Show answer
Use mockRejectedValue with an Error, append the component, wait for pending promises, and assert the error state.