# How do you mock wired Salesforce data adapters when writing Jest unit tests for LWC?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, Jest Testing, Wire Mocking

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-you-mock-wired-salesforce-data-adapters-when-writing-jest-unit-tests-for-lwc

## Answer

**Basics:** Jest tests run in Node without a Salesforce server, so `@wire` adapters have to be replaced with test doubles. `@salesforce/sfdx-lwc-jest` supplies stubs for `lightning/*` modules and `@salesforce/*` imports, plus helpers to emit data to wired components.

**How it works:** For LDS adapters such as `getRecord`, import it from `lightning/uiRecordApi`; the stub exposes `getRecord.emit(mockData)` and `getRecord.error()`. For a wired Apex method, mock the module with `createApexTestWireAdapter` (see the example), then call `emit()` on the imported method.

**Advanced / deep dive:** Create the element with `createElement('c-my-cmp', { is: MyCmp })`, append it to `document.body`, then call `emit`. Rendering after emit is asynchronous, so await a microtask (`await Promise.resolve()` or a `flushPromises` helper) before assertions. Imperative Apex is mocked with `jest.mock('@salesforce/apex/Ctrl.method', () => ({ default: jest.fn() }), { virtual: true })` and `method.mockResolvedValue(data)` or `mockRejectedValue(err)`. Emit data matching the real shape (`fields.Name.value`), and test error shapes `{ body: { message }, status }`. Always clean up in `afterEach` by removing created elements and calling `jest.clearAllMocks()` so state does not leak between tests. Base components such as `lightning-datatable` are stubs, so you assert on attributes passed in, not on their rendered internals. Navigation, toasts and message services can be tested by mocking the module or listening for dispatched events.

**Code / config example:**
```javascript
import { createElement } from 'lwc';
import { createApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import { getRecord } from 'lightning/uiRecordApi';
import getContacts from '@salesforce/apex/ContactCtrl.getContacts';
import ContactList from 'c/contactList';

jest.mock('@salesforce/apex/ContactCtrl.getContacts',
    () => ({ default: createApexTestWireAdapter(jest.fn()) }), { virtual: true });

afterEach(() => { while (document.body.firstChild) document.body.removeChild(document.body.firstChild); });

it('renders contacts', async () => {
    const el = createElement('c-contact-list', { is: ContactList });
    document.body.appendChild(el);
    getContacts.emit([{ Id: '003x', Name: 'Ada' }]);
    await Promise.resolve();
    expect(el.shadowRoot.querySelectorAll('li').length).toBe(1);
});
it('handles error', async () => {
    const el = createElement('c-contact-list', { is: ContactList });
    document.body.appendChild(el);
    getContacts.error();
    await Promise.resolve();
    expect(el.shadowRoot.querySelector('.error')).not.toBeNull();
});
```

**Hidden gotchas & must-remember points:**
- `emit()` before the element is appended has no effect.
- You must await a microtask after emit before asserting the DOM.
- Mock shapes must match what the real adapter returns, or tests pass while production fails.
- Wire adapter mocks apply per test file; reset between tests.
- Base components are stubs; they do not run real behavior.
- Jest tests are not required for deployment and do not count toward Apex coverage.

**Best practice:** Test behavior, not implementation: emit realistic data, await rendering, assert on visible output and dispatched events.

---
Source: ForceChallenges · last updated 2026-11-02
