Sub topic 2
Install sfdx-lwc-jest and run your first test
This chapter assumes you know basic Lightning web components (templates, @api properties, event handlers). It also assumes you have Node.js and npm installed and can work in a Salesforce DX project. You will install the test tooling, add a configuration file and npm scripts, and run one passing test.
What sfdx-lwc-jest provides
Jest is a JavaScript test runner. It does not know how to compile Lightning web components, resolve c/counter imports, or load @salesforce/* modules. The @salesforce/sfdx-lwc-jest package fills that gap. It supplies a Jest configuration, a transformer that compiles LWC code, and stub versions of the platform modules. Tests then run in Node.js with no org connection.
Install the package
Run this from the root of your Salesforce DX project. The root is the folder that contains sfdx-project.json.
npm init -y
npm install @salesforce/sfdx-lwc-jest --save-devIf your project already has a package.json, skip npm init -y. The install adds Jest as a dependency, so you do not install Jest separately.
Configure Jest
Create jest.config.js at the project root. It starts from the configuration that the package ships and adds one setting.
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};The spread (...jestConfig) keeps the defaults. modulePathIgnorePatterns stops Jest from scanning the .localdevserver folder, which can produce duplicate-module warnings.
Add npm scripts
Add these entries to package.json. Arguments after the double dash go to Jest itself.
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}The component under test
The examples in this tutorial use a small counter. Create force-app/main/default/lwc/counter/counter.html:
<template>
<p class="count">{count}</p>
<button onclick={handleClick}>Add</button>
</template>Then create counter.js in the same folder:
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 } })
);
}
}Write the first test
Jest finds test files by name and location. Put them in a __tests__ folder inside the component folder, and end the file name with .test.js. Create force-app/main/default/lwc/counter/__tests__/counter.test.js:
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
it('starts at zero', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const count = element.shadowRoot.querySelector('.count');
expect(count.textContent).toBe('0');
});
});The test builds the component, attaches it to the page, reads the rendered paragraph, and checks its text. Later chapters explain each of these steps in detail. For now, you only need to see the test run.
Run the tests
npm run test:unitA passing run prints the test file with a green PASS and a summary similar to Tests: 1 passed, 1 total.
Common setup errors
- No tests found: the file is not inside a
__tests__folder, or its name does not end in.test.js. - Cannot find module
c/counter: you ranjestdirectly instead ofsfdx-lwc-jest, so the LWC module resolver was not loaded. document is not defined: the same cause. Use the npm script.
Exercise
You run npx jest and get "Cannot find module 'c/counter'", but npm run test:unit passes. Why?
Show answer
The test:unit script calls sfdx-lwc-jest, which applies the LWC resolver, transformer, and DOM environment from jestConfig. Plain jest does not load that configuration, so it cannot resolve the c/ namespace.