Sub topic 1
Setting up Jest for LWC
Lightning Web Components (LWC) run in a browser inside a Salesforce org. Unit tests for them run in Node.js, on your machine, with no org. This chapter covers the tooling that makes that possible: the @salesforce/sfdx-lwc-jest package, its configuration, where test files go, and how to run them. Later chapters build on this setup to mock wire adapters and Apex.
Prerequisites
This chapter assumes you already have the following.
- A Salesforce DX project (a folder with
sfdx-project.json) containing at least one LWC bundle. - Node.js and npm installed, using a Node.js version that your installed
@salesforce/sfdx-lwc-jestrelease supports. Check the package's README if installation fails with an engine warning. - Basic LWC knowledge: templates, the
@apidecorator, and lifecycle hooks. - Basic Jest vocabulary:
describe,it,expect, andjest.fn. - Comfort with promises and
async/await.
You do not need a Salesforce org or a Salesforce CLI login to run unit tests.
What the tooling does
Jest is a general JavaScript test runner. By default it knows nothing about LWC. It cannot compile a .html template, it does not understand @wire or @api, and it cannot resolve an import such as c/contactList or lightning/uiRecordApi.
@salesforce/sfdx-lwc-jest fills those gaps. It bundles a Jest preset, a transformer, and a module resolver. The preset configures Jest to run in a simulated browser (jsdom). The transformer compiles LWC source files, including templates and decorators. The resolver maps module names to files or to stand-in modules.
The table shows how common import paths resolve in a test.
| Import in component code | What Jest loads in a test |
|---|---|
| `c/greeting` | The component bundle from your project's `lwc` folders |
| `lightning/button` and other base components | A lightweight stub, not the real component |
| `lightning/uiRecordApi` and similar | A stub module with test wire adapters (covered in a later chapter) |
| `@salesforce/apex/Class.method` | No real module exists. You supply a mock (covered in a later chapter) |
| `@salesforce/label/...`, `@salesforce/user/...` | A stand-in value |
The diagram shows the path from a command to a running test.
Installing the package
From the root of your Salesforce DX project, install the package as a development dependency.
npm install @salesforce/sfdx-lwc-jest --save-devProjects created with the Salesforce CLI or the VS Code extensions often come with this already. If your package.json lists it under devDependencies, you only need to run npm install.
The package pulls in Jest and the LWC compiler pieces it needs, so you normally do not install jest separately. Installing a second, different Jest version is a common source of confusing errors.
Configuring Jest
Jest reads a jest.config.js file in the project root. The package exports a ready-made configuration, so your file can be very short.
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};The spread (...jestConfig) copies in the preset, the transformer settings, and the resolver. You then add your own options after it. The modulePathIgnorePatterns line keeps Jest from scanning a local development server folder that can contain duplicate component copies.
If you need a setup file that runs before every test file, add the setupFiles option. Spread the package's jestConfig.setupFiles first, so you extend the defaults instead of replacing them.
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
setupFiles: [...(jestConfig.setupFiles || []), '<rootDir>/jest-setup.js'],
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};Replacing setupFiles outright is a quiet way to break the preset. It will not always fail loudly.
Adding npm scripts
Add scripts to package.json so everyone on the team runs tests the same way.
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:debug": "sfdx-lwc-jest -- --debug",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}Each script calls the sfdx-lwc-jest command, which wraps Jest. Arguments after the -- separator go to Jest. Run a script with npm run, for example npm run test:unit:watch. Watch mode reruns only tests related to files you changed, which makes it the best choice while you write tests.
To run one test file, pass a path pattern through npm.
npm run test:unit -- contactListJest treats contactList as a pattern and runs every test file whose path contains it.
Where test files live
By convention, a component's tests live in a __tests__ folder inside the component bundle. The file name ends in .test.js.
force-app/main/default/lwc/
greeting/
greeting.html
greeting.js
greeting.js-meta.xml
__tests__/
greeting.test.jsJest finds files in __tests__ folders and files that match *.test.js or *.spec.js. Salesforce deployment tools ignore __tests__ folders, so your tests do not get pushed to the org with the component. The default .forceignore generated by Salesforce DX already covers this. If you moved tests to another folder, check .forceignore before you deploy.
A smoke test
Before you mock anything, confirm the setup works end to end with a trivial component. Here is the component.
// greeting.js
import { LightningElement, api } from 'lwc';
export default class Greeting extends LightningElement {
@api name = 'World';
}And its template.
<!-- greeting.html -->
<template>
<p class="greeting">Hello, {name}!</p>
</template>Now the test file.
// __tests__/greeting.test.js
import { createElement } from 'lwc';
import Greeting from 'c/greeting';
describe('c-greeting', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the default name', () => {
const element = createElement('c-greeting', { is: Greeting });
document.body.appendChild(element);
const paragraph = element.shadowRoot.querySelector('.greeting');
expect(paragraph.textContent).toBe('Hello, World!');
});
});Run npm run test:unit. You should see one passing test. This test exercises each piece of the setup. The transformer compiled the template and the decorator. The resolver turned c/greeting into the bundle path. Jest ran the test in jsdom, where document exists.
The next chapter explains createElement, attaching to the DOM, and the cleanup block in detail. For now, treat them as the standard skeleton.
Why unit tests cannot use the real wire service
You may wonder why this setup needs stubs at all. In an org, the platform supplies the wire service. It is the runtime that connects @wire to adapters such as getRecord, handles caching, and calls Apex over the network. None of that runs in Node.js.
So sfdx-lwc-jest replaces those modules with stubs. Base components under lightning/* become simple placeholders. That is why element.shadowRoot.querySelector('lightning-button') finds an element in a test, but clicking it does not run Salesforce's button logic. Data modules such as lightning/uiRecordApi become stubs whose adapters your test can drive. Apex imports have no real implementation, so each test file must supply one. Later chapters cover that in depth.
Your tests check your component's logic: what it renders for given data and what it sends when a user acts. They do not check the platform.
Common setup problems
The table lists the errors you are most likely to see when setting up, with their usual causes.
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module 'c/greeting'` | Jest is not running from the project root, or the bundle is outside the folders listed in `sfdx-project.json` | Run from the project root and check `packageDirectories` |
| `Cannot find module '@salesforce/sfdx-lwc-jest/config'` | Package not installed | Run `npm install` |
| Test file is never found | File is not named `*.test.js` or `*.spec.js`, or sits outside the project | Rename it and place it in the bundle's `__tests__` folder |
| Syntax error on `@wire` or `@api` | `jest.config.js` does not spread `jestConfig`, so the transformer is missing | Spread the exported config as shown above |
| `document is not defined` | A custom `testEnvironment` replaced jsdom | Remove the override or set it back to jsdom |
| Odd failures after adding a second Jest | Two Jest versions are installed | Remove the extra `jest` dependency |
Debugging a run
If a test behaves strangely, three tools help.
- Use
console.log(element.shadowRoot.innerHTML)to see exactly what rendered. Seeing the markup often explains a failedquerySelector. - Use
--debug(thetest:unit:debugscript) to run Jest with the Node inspector attached. Openchrome://inspectin Chrome to connect. - Use
--coverageto produce a coverage report. It shows which branches of your component your tests never reached, which is useful for finding untested error paths.
Exercise
You add setupFiles: ['<rootDir>/jest-setup.js'] to your jest.config.js after spreading jestConfig, and now many LWC tests fail with unrelated errors. What probably happened, and how do you fix it?
Show answer
Your setupFiles array replaced the one from jestConfig, which removed setup files the preset needs. Spread the existing entries first: setupFiles: [...(jestConfig.setupFiles || []), '<rootDir>/jest-setup.js'].
Exercise
A teammate puts greeting.test.js in force-app/main/default/lwc/greeting/ instead of in a __tests__ subfolder. Jest still runs it. Why might that still be a problem?
Show answer
Jest matches the .test.js name, so it runs the file. But deployment tools only ignore __tests__ folders, so the test file would be treated as part of the component bundle and could cause a deployment error or ship test code to the org. Move it into __tests__.