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.