Sub topic 1
Why test Lightning web components with Jest
Jest is a JavaScript test runner. The sfdx-lwc-jest package adapts Jest for Lightning web components (LWCs). It renders a component in a simulated browser, so you can test component behavior without deploying to a Salesforce org.
Unit tests check one component in isolation. They catch broken rendering, event behavior, and asynchronous updates early. They also document what the component promises to its users.
Prerequisites
This chapter assumes that you understand LWC templates, @api properties, and event handling. You also need Node.js, npm, and a Salesforce DX project.
Install `sfdx-lwc-jest` and run your first test
Install the test package as a development dependency:
npm install --save-dev @salesforce/sfdx-lwc-jestCreate jest.config.js in the project root:
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};Add a script to package.json, then run it:
{
"scripts": {
"test:unit": "sfdx-lwc-jest"
}
}npm run test:unitJest finds files ending in .test.js, including tests inside an LWC folder.
Anatomy of a Jest test
A test normally has four parts:
describegroups tests for one component.itstates one behavior.- Setup creates and attaches the component.
expectchecks the result.
The test lifecycle hook afterEach removes the component after every test. This prevents one test from changing the next test's starting state.
Render a component with `createElement`
Import the component class and use createElement with its custom element name:
import { createElement } from 'lwc';
import Counter from 'c/counter';
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);Attaching the element starts its normal LWC lifecycle. The is option connects the tag name to the imported component class.
Query and assert on the shadow DOM
An LWC's rendered markup is inside its shadow root. Query it through element.shadowRoot:
it('renders the initial count', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});Use selectors that describe user-visible behavior, such as a button or a text class. Avoid testing internal implementation details when a public result is available.
Exercise
Which object should you use to find an element rendered by an LWC?
Show answer
Use the component's shadowRoot, such as element.shadowRoot.querySelector('button').