Sub topic 3
Why wire adapters and Apex need mocks
This chapter explains why a Jest test for a Lightning Web Component (LWC) cannot reach real data. It also covers what that means for how you write the test. The later chapters show the mechanics. Here you build the reasoning that makes those mechanics make sense.
You should already know basic LWC (templates, decorators, lifecycle hooks), how @wire works, how to import an Apex method, basic Jest (describe, it, expect, jest.fn), and promises with async/await.
What a component test actually runs
A Jest test for an LWC runs in Node.js, not in a browser and not in Salesforce. The sfdx-lwc-jest package supplies a simulated DOM (jsdom) and a transformer that compiles your component's HTML and JavaScript so the LWC engine can render it there.
Several things that exist in an org do not exist in this environment:
- No Salesforce server answers requests.
- No Apex classes are deployed, so there is nothing to execute.
- No Lightning Data Service (LDS) cache holds records.
- No user session or sharing rules apply.
Your component code does not know this. When it declares @wire(getRecord, ...) or calls an imported Apex method, it expects something to answer. The test has to provide that answer.
The two data paths
Components in the examples of this tutorial get server data in two ways.
Wire. A decorated property or function receives data from a wire adapter. The adapter is a piece of platform code that the component's @wire decorator connects to. The adapter provisions values ({ data, error }) whenever its inputs change. Built-in adapters such as getRecord from lightning/uiRecordApi use LDS. Wired Apex methods use an adapter built from the Apex import.
Imperative. The component calls an imported Apex method as a function, such as findContacts({ searchTerm }). The call returns a promise, and your code handles it with then/catch or await.
Here is a small wired component. The next chapters build tests for it.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:if={contacts.error}>
<p class="error">Could not load contacts.</p>
</template>
</template>import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
@wire(getContactList)
contacts;
}In an org, the platform runs ContactController.getContactList, the adapter delivers a result, and the component re-renders. In Jest, none of that happens unless you arrange it.
What happens if you do not mock
The behavior depends on the path and on your sfdx-lwc-jest version, but the pattern is consistent: the test environment either has no data source or a placeholder that never produces useful data.
| Data source | Without your mock | Effect on the test |
|---|---|---|
| Wired Apex method | The import resolves to a default stub from the Jest transformer, which provides no data. | The wire never emits, so `contacts.data` and `contacts.error` stay `undefined`. The component renders its empty state. |
| Imperative Apex method | The default stub returns a promise that resolves with `undefined`. | The component runs its success handler with no result. Your assertions about rendered items fail or pass for the wrong reason. |
| Built-in adapter such as `getRecord` | `sfdx-lwc-jest` ships a stub for `lightning/uiRecordApi`. | The stub exists but is idle until the test calls `emit`. |
| Any request to a real server | Nothing is listening. | There is no network path to an org. |
The key point: the missing mock does not usually crash with a clear message. It lets the test run against a data source that says nothing. A test that only checks "the component renders" will pass even when the data path is broken.
Why not call a real org?
You might ask whether the tests could reach a scratch org and use real data. That is a different kind of test, and Jest component tests deliberately avoid it. Compare the options:
| Concern | Real org | Mocked data source |
|---|---|---|
| Speed | Seconds per call, plus authentication | Milliseconds |
| Determinism | Results change with org data, limits, and deployments | The same input produces the same output every run |
| Error paths | Hard to trigger a server error or a sharing failure on demand | One line makes the source fail |
| Edge data | You must create records with the right shape | You write the object literal you need |
| Environment | Needs a connected org and credentials in CI | Needs only Node.js |
Mocking also keeps the test focused. A component test should answer "given this data, does the component render and behave correctly?" It should not also answer "does the Apex query return the right rows?" The Apex class has its own tests in Apex.
The seam: a mock replaces the import
Both paths share one idea. The component never talks to the server directly. It talks to an import:
@salesforce/apex/ContactController.getContactListlightning/uiRecordApi
Jest controls what module an import resolves to. If a test replaces the module with a fake, the component receives the fake without any change to the component code. The import is the seam where you cut the component off from the platform.
What you mock depends on the path:
- For wire, you replace the adapter with a test wire adapter. It is a real wire adapter in shape, but it adds an
emitmethod (to push data) and anerrormethod (to push an error). The test drives the component by calling them. - For imperative Apex, you replace the import with a
jest.fn(). You then choose what the promise does withmockResolvedValueormockRejectedValue, and you can inspect calls withtoHaveBeenCalledWith.
What a mock gives you
A mock does three jobs for a test.
- Supplies input. You choose the data the component sees. That includes the loading state (nothing emitted yet), success, an error, and empty results.
- Records output. A
jest.fnremembers its calls. A test can check that the component sent{ searchTerm: 'Amy' }and not something else. - Controls timing. The mock responds only when the test says so. You decide when data arrives, which lets you assert on each stage of the component's life.
The third job matters because rendering is asynchronous. After you emit data, the component re-renders on a later microtask. The test must wait for that before it checks the DOM. The next chapter covers this in detail.
A first look at the shape of a mock
You do not need to master the syntax yet. This preview shows how small the change is. The wired Apex import is replaced by a test adapter, and the test pushes one record list through it.
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 }
);
it('renders what the wire emits', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
await Promise.resolve();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
document.body.removeChild(element);
});Three things to notice:
- The test imports
getContactListas usual. Afterjest.mock, that import is the test adapter, not the Apex method. - The component file is unchanged. It still imports the same path.
emitplays the role of the server response.
The { virtual: true } option tells Jest the module may not exist on disk. Apex imports have no real file, so without it Jest reports that it cannot find the module. Later chapters return to this under common pitfalls.
What you should not mock
Mocking everything is as unhelpful as mocking nothing. Keep these guidelines in mind:
- Mock the boundary, not your own code. Replace the Apex import and wire adapters. Do not replace the component's own methods or child components you wrote, unless the test is about isolating one of them.
- Do not mock the thing you are testing. If you mock the component's handler, you test the mock.
- Keep mock data realistic. If Apex returns objects with
IdandName, your mock data should use the same field names. A mock that returns{ id, name }can pass while the real response breaks the template. - Accept the limits. A mocked test cannot catch a wrong Apex query, a missing field-level permission, or an
@AuraEnabledannotation left off the method. Cover those with Apex tests and org-level checks.
Putting it together
The reasons to mock, in order of how often they matter in practice:
- The test environment has no server, so there is nothing to answer a wire or an Apex call.
- Default stubs stay silent, so a test without a mock can pass while checking nothing.
- Error and empty paths are hard to trigger for real, but easy to trigger with a mock.
- Mocks record how the component called the data source, so you can assert on the inputs.
- Mocks make tests fast and repeatable, so you can run them on every commit.
Exercise
A component imports an Apex method and calls it imperatively. A developer writes a Jest test with no mock for that import. The test clicks the button, waits, and asserts that the component renders the text "No results". The test passes. Why is this result unreliable, and what is the smallest change that makes the test meaningful?
Show answer
Without a mock, the import resolves to a default stub whose promise resolves with undefined. The component receives no data, so it may show "No results" regardless of what the real Apex method would return. The test therefore passes without exercising the real data path, and it cannot tell a working component from a broken one. The smallest change is to replace the import with jest.fn() through jest.mock(..., () => ({ default: jest.fn() }), { virtual: true }). Then call mockResolvedValue([]) for the empty case and mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]) for the success case, and assert different output for each.
Exercise
Name two things a mocked Jest test cannot verify about an Apex-backed component, and say where each should be tested instead.
Show answer
It cannot verify that the Apex query returns the correct rows, and it cannot verify that the method is annotated @AuraEnabled or respects sharing and field-level security. Test the query logic and security behavior with Apex unit tests. Check the end-to-end connection in a sandbox or scratch org, for example with a UI or integration test.