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 for debounced code.