Sub topic 2
Install sfdx-lwc-jest and run your first test
This chapter sets up Jest in a Salesforce DX project, explains what the configuration does, and runs one passing test. I assume you can read a Lightning web component (LWC), have Node.js and npm installed, and have an existing Salesforce DX project. You don't need an org connection. Everything here runs locally.
What sfdx-lwc-jest provides
Jest is a general JavaScript test runner. It doesn't know how to compile LWC templates, resolve imports like c/counter, or handle imports like @salesforce/apex/.... The @salesforce/sfdx-lwc-jest package fills those gaps. It supplies:
- A transformer that compiles LWC
.htmland.jsfiles so Jest can load them. - A module resolver that maps
c/componentNameto folders under your package directories. - Stubs for
@salesforce/*modules (Apex, schema, labels, user and so on) and for the base Lightning components such aslightning-button. - A jsdom test environment, which gives tests a simulated browser
document.
Your tests then run in Node.js against that simulated browser. No deployment or org is involved.
Install the package
From the root of your project (the folder with sfdx-project.json), initialize npm if the project has no package.json:
npm init -yThen install the package as a development dependency:
npm install @salesforce/sfdx-lwc-jest --save-devThis also installs Jest. It adds node_modules to your project, which should already be in .gitignore. Projects created from recent Salesforce DX templates often include a package.json with these dependencies already declared. In that case, npm install is enough.
Check the install:
npx sfdx-lwc-jest --helpIf the command prints usage text, the package is available.
Add the Jest configuration
Create jest.config.js at the project root:
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};Line by line:
require('@salesforce/sfdx-lwc-jest/config')loads the default configuration shipped with the package. It contains the transformer, resolver, stub mappings, and environment settings....jestConfigcopies all those defaults into your config object.modulePathIgnorePatternsis your own addition. It tells Jest to skip the.localdevserverfolder, which the Salesforce local development tooling can create. Without this, Jest can report duplicate component names.
Because you spread the defaults first, you can override or add any Jest option after them. Later chapters do this for coverage settings. Put your overrides after ...jestConfig, or the defaults will replace them.
Add npm scripts
Add a scripts section to package.json. Keep the other keys in the file as they are:
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}| Script | What it does |
|---|---|
| `test:unit` | Runs every test once and exits. Use it locally and in continuous integration. |
| `test:unit:watch` | Reruns tests affected by files you change. Use it while you write code. |
| `test:unit:coverage` | Runs all tests once and prints a coverage report. |
Arguments after the double dash (--) go to Jest itself. So sfdx-lwc-jest -- --watch runs Jest with its --watch option.
Where test files live
By convention, each component keeps its tests in a __tests__ folder inside its own bundle:
force-app/main/default/lwc/counter/
├── counter.html
├── counter.js
├── counter.js-meta.xml
└── __tests__/
└── counter.test.jsJest finds files that match *.test.js or sit in a __tests__ folder. The default .forceignore in a DX project excludes __tests__ folders, so test files are not deployed to your org.
A component to test
This chapter uses a small counter component. The template is counter.html:
<template>
<p class="count">{count}</p>
<button onclick={handleClick}>Add</button>
</template>The class is counter.js:
import { LightningElement, api } from 'lwc';
export default class Counter extends LightningElement {
@api step = 1;
count = 0;
handleClick() {
this.count += this.step;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}The component has a public step property, a count field that starts at 0, and a click handler that adds step to count and dispatches a countchange event. This chapter only checks the starting state. Clicking and events come in later chapters.
Write the first test
Create force-app/main/default/lwc/counter/__tests__/counter.test.js:
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
it('renders a starting count of 0', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const count = element.shadowRoot.querySelector('.count');
expect(count.textContent).toBe('0');
});
});What each part does:
createElementcomes from thelwcmodule. It builds an instance of your component class.import Counter from 'c/counter'loads the component. Thecnamespace points to your project'slwcfolders through the resolver.document.body.appendChild(element)attaches the element. The component renders at that point.element.shadowRoot.querySelector('.count')finds the paragraph in the component's shadow DOM.expect(...).toBe('0')asserts on the text. The rendered text is a string, so compare with'0', not the number0.
The first render happens synchronously when you attach the element, so this test needs no waiting. Later chapters cover re-rendering after a change, and cleaning up document.body between tests. This single test skips cleanup because only one test runs.
Run it
npm run test:unitA passing run looks like this:
PASS force-app/main/default/lwc/counter/__tests__/counter.test.js
c-counter
✓ renders a starting count of 0 (21 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 totalTry breaking the test on purpose. Change '0' to '1' and run again. Jest prints the expected and received values and points to the failing line. Seeing a test fail for the right reason confirms that the test checks something real.
For a single file or name pattern, call Jest directly. It reads the same jest.config.js:
npx jest counterUse watch mode while developing:
npm run test:unit:watchIn watch mode, press a to run all tests, p to filter by file name, and q to quit.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `jest` or `sfdx-lwc-jest` is not recognized | Dependencies not installed | Run `npm install` in the project root. |
| `SyntaxError: Cannot use import statement outside a module` | Jest ran without the sfdx-lwc-jest transformer | Check that `jest.config.js` exists at the root and spreads `jestConfig`. |
| `Cannot find module 'c/counter'` | The resolver can't map the namespace to your component | Check the path in `sfdx-project.json` under `packageDirectories`, and that the folder and file names match the import. |
| `Cannot find module 'lwc'` | The package is missing or installed in a different folder | Install it in the folder that holds `jest.config.js`. |
| `Duplicate module` warnings | Another folder contains copies of your components | Add the folder to `modulePathIgnorePatterns`. |
| No tests found | The file is not named `*.test.js` and is not in `__tests__` | Rename the file or move it. |
The resolver reads sfdx-project.json, so a project with several package directories needs no extra mapping. Every listed directory is searched for an lwc folder.
Check your understanding
Exercise
Your package.json has the script "test:unit:coverage": "sfdx-lwc-jest -- --coverage". What is the purpose of the -- in that command, and how would you write a script that runs Jest in watch mode?
Show answer
Arguments after -- are passed through to Jest, so --coverage is a Jest option, not an sfdx-lwc-jest option. A watch mode script is "test:unit:watch": "sfdx-lwc-jest -- --watch".
Exercise
A teammate adds modulePathIgnorePatterns: ['<rootDir>/.localdevserver'] to jest.config.js before the ...jestConfig line and later notices the setting has no effect. Why, and how do you fix it?
Show answer
Object spread copies the default properties over any keys defined earlier, so the defaults replace the teammate's value. Move the override after ...jestConfig.
Exercise
Your test file imports c/counter and Jest reports Cannot find module 'c/counter'. Name two things to check.
Show answer
Check that jest.config.js spreads the sfdx-lwc-jest jestConfig, so the resolver is active. Check that the component folder sits under a path listed in packageDirectories in sfdx-project.json, and that the folder and file names match the import (counter).