# What is the role of Jest in unit testing Lightning Web Components, and how does it mock Salesforce modules?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, Jest Testing, Unit Testing

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-the-role-of-jest-in-unit-testing-lightning-web-components-and-how-does-it-mock-salesforce-modules

## Answer

**Basics:** A unit test mounts one component in a fake DOM (jsdom), triggers events or data, and asserts output. It is fast, runs in CI, and needs no deployment. Install with `sfdx force:lightning:lwc:test:setup` (older) or via `npm install` of the `@salesforce/sfdx-lwc-jest` dev dependency in an SFDX project, then run `npm run test:unit`.

**How it works:** Tests live in a `__tests__` folder beside the component. You create the component with `createElement('c-name', { is: Cmp })`, append to `document.body`, interact (`el.shadowRoot.querySelector`, dispatch events), and await promises for re-render. The Jest resolver maps Salesforce modules: `@salesforce/apex/*` and `@salesforce/schema/*` become stubs, `@salesforce/label/*` and `@salesforce/user/*` resolve to placeholders, `lightning/*` base components render as simple stubs, and wire adapters offer `emit()`/`error()`.

**Advanced / deep dive:** Mock imperative Apex with `jest.mock('@salesforce/apex/C.m', () => ({ default: jest.fn() }), { virtual: true })`. Mock wired Apex with `createApexTestWireAdapter`, LDS adapters via their emit method, and custom or newer adapters with `registerTestWireAdapter`-style helpers from the package. Test child-to-parent communication by listening for CustomEvents, and parent-to-child by setting `@api` properties and awaiting re-render. Coverage reports via `--coverage`. Limits: Jest cannot test real SOQL, sharing, FLS, base component internals, or navigation without mocks, so combine it with Apex tests and a few UI/E2E tests (for example UTAM or Selenium-based). Salesforce does not enforce JavaScript coverage for deployment. Keep tests isolated by cleaning the DOM and clearing mocks after each test, and use `jest.useFakeTimers()` for debounced code.

**Code / config example:**
```javascript
import { createElement } from 'lwc';
import Greeter from 'c/greeter';

describe('c-greeter', () => {
    afterEach(() => { while (document.body.firstChild) document.body.removeChild(document.body.firstChild); });

    it('fires an event on click', async () => {
        const el = createElement('c-greeter', { is: Greeter });
        document.body.appendChild(el);
        const handler = jest.fn();
        el.addEventListener('greet', handler);
        el.shadowRoot.querySelector('button').click();
        await Promise.resolve();
        expect(handler).toHaveBeenCalledTimes(1);
    });
});
```

**Hidden gotchas & must-remember points:**
- Rendering is async; always await a microtask before asserting.
- Base components are stubs; they do not validate or call the server.
- `jest.mock` for Apex needs `{ virtual: true }`.
- Clean up DOM and mocks after every test to prevent leakage.
- Jest tests do not count toward Apex code coverage or deploy gates.
- Test through public APIs (`@api`, events, DOM), not private fields.

**Best practice:** Run Jest in CI on every pull request and cover rendering, events, error states and wire data shapes.

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