Sub topic 1
Why test Lightning web components with Jest
Lightning web components (LWC) run in a browser, so many developers check them by deploying to an org and clicking through the page. That works for a first draft. It is slow and hard to repeat. This chapter explains what Jest unit tests give you for LWC, how they run without an org, and what they cannot tell you. The rest of the tutorial builds the skills one step at a time.
Prerequisites
This chapter assumes you already have the following:
- Basic knowledge of Lightning web components: templates,
@apiproperties, and event handling. - Working knowledge of modern JavaScript, including promises and
async/await. - Node.js and npm installed on your machine.
- Basic familiarity with a Salesforce DX project and its folder layout.
You do not need any Jest experience. You do not need an org for any step in this tutorial.
What a Jest unit test of a component is
A unit test runs a small piece of code in isolation and checks its behavior against an expectation. For a Lightning web component, the unit is the component. The test creates an instance, gives it input, and checks what it renders and which events it fires.
Jest is a JavaScript test runner from the Node.js ecosystem. It finds test files, runs them, reports failures, and provides tools for mocking dependencies. Salesforce publishes @salesforce/sfdx-lwc-jest, a package that configures Jest so it understands LWC code. The test runs in Node.js, not in a browser and not on Salesforce servers.
The following table compares the two ways of checking a component.
| Question | Check by deploying to an org | Check with Jest |
|---|---|---|
| Needs an org or login | Yes | No |
| Time to see a result | Deploy, open the page, click | Usually a second or two |
| Repeatable by a teammate or CI server | Only with manual steps | Yes, with one command |
| Covers rare cases (errors, empty data) | Hard to trigger real data | Easy to simulate |
| Shows real platform behavior | Yes | No |
What you gain
Fast feedback
A test run needs no deployment, so you can run tests on every save. Watch mode, which you will set up in the next chapter, reruns only the tests affected by your change. A failing assertion points at the line that broke, which is faster than finding a problem by clicking through a page.
Repeatable checks for edge cases
Some component states are hard to produce in a real org:
- A server call that fails.
- A list with no records.
- A list with thousands of records.
- A property set to
undefined.
In a test you set up the state directly. You can make a mocked Apex method reject with an error and check that the component shows the message. The same test then runs the same way every time.
Safety when changing code
A component often changes after its first release. A test suite records what the component should do. When you refactor a handler or rename a property, the tests tell you right away if the visible behavior changed. This matters most for code written by someone else, where you may not know every behavior that other code depends on.
Tests as documentation
A test named adds the step to the count and fires countchange states a requirement in a form that stays correct, because a failing test forces someone to update it. A new developer can read the tests to learn how the component is meant to be used.
Automation in a pipeline
Jest runs from the command line and exits with a non-zero status when a test fails. A continuous integration job can run it on every pull request and block a merge when tests fail. It needs only Node.js, not org credentials, so the job is simple to set up.
How the tests run without an org
A Lightning web component imports things that only exist on the platform, such as @salesforce/apex/... or lightning/navigation. Node.js cannot resolve those imports. The sfdx-lwc-jest package fills the gap with four pieces:
- A transformer. It compiles component files, including templates, into JavaScript that Jest can load. It uses the same LWC compiler the platform uses.
- A resolver. It maps the
c/namespace, as inimport Counter from 'c/counter', to the component folders in your project. - A DOM implementation. Jest uses jsdom, a JavaScript implementation of browser APIs such as
documentandElement. This is whydocument.body.appendChildworks in a test. - Stubs for platform modules and base components. Imports such as
@salesforce/schema/...and tags such aslightning-buttonresolve to simple stand-in versions supplied by the package. You replace them with mocks when a test needs specific behavior.
The following diagram shows how a test reaches your component.
What a first test looks like
You will build a real component test starting in the next chapter. To see how small a Jest test is, here is a plain JavaScript function and its test. The function could live in a shared utility module of your project.
// force-app/main/default/lwc/utils/clamp.js
export function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}// force-app/main/default/lwc/utils/__tests__/clamp.test.js
import { clamp } from '../clamp';
describe('clamp', () => {
it('returns the value when it is inside the range', () => {
expect(clamp(5, 0, 10)).toBe(5);
});
it('limits the value to the minimum and maximum', () => {
expect(clamp(-3, 0, 10)).toBe(0);
expect(clamp(42, 0, 10)).toBe(10);
});
});Notice the pattern. describe groups tests, it defines one scenario, and expect(...).toBe(...) states what must be true. Testing a component follows the same pattern. The difference is that the test first creates the component and then inspects the DOM it rendered.
Test files go in a folder named __tests__ inside the component's own folder, and their names end in .test.js. The default configuration looks for files in that location.
What unit tests do not cover
Jest tests are fast because they leave out the real platform. That gap defines what you still need other checks for.
- Real Apex and data. A mocked Apex method returns what you tell it to. A test cannot show that the Apex class exists, compiles, or returns that shape. Apex has its own tests.
- Real Lightning base components. Stubs do not reproduce the rendering or validation of
lightning-inputorlightning-datatable. Your test can check which attributes you pass to a base component. It cannot check how that component looks. - Styling and layout. jsdom does not compute real layout, so CSS, SLDS classes, and responsive behavior are not checked.
- Platform security. Lightning Web Security or Lightning Locker, sharing rules, and field-level security apply only on the platform.
- Page integration. Whether a component works in a Lightning page, a record page, or an Experience Cloud site needs a manual or end-to-end check.
Teams usually combine three layers. Many fast Jest tests cover component logic. Apex tests cover server code. A small number of end-to-end or manual checks cover real integration. Jest handles the first layer.
Common mistakes when starting out
- Testing implementation instead of behavior. A test that reads private fields or calls internal methods breaks whenever you refactor. Check what a user or a parent component can observe: rendered text, attributes, and dispatched events.
- Treating coverage as the goal. A test can run every line and assert nothing. Coverage shows which code ran, not whether the behavior was checked. The last chapter covers using it well.
- Skipping error and empty-state tests. These are the cases Jest makes easy and manual checks make hard. Test them early.
- Sharing state between tests. A component left in
document.bodyby one test can affect the next. Clean up after each test, as a later chapter shows.
What the following chapters cover
The next chapter installs sfdx-lwc-jest and runs a first test from the command line. Later chapters render components with createElement, query the shadow DOM, wait for re-rendering, and test properties and events. They finish with mocking Apex, wire adapters, platform modules, and using coverage and debugging tools.
Exercise
A component calls an Apex method to load contacts. List two things a Jest test can verify about it and one thing it cannot.
Show answer
A Jest test can verify that the component calls the Apex method and renders the returned records, and that it shows an error message when the mocked method rejects. It cannot verify that the real Apex class exists, compiles, or returns data in the shape the mock supplies, because the Apex call is replaced by a mock. Apex tests and a check in an org cover that.
Exercise
Why does a Jest test for a Lightning web component not need an org, even though the component imports modules such as @salesforce/apex/ContactController.getContacts?
Show answer
The tests run in Node.js with jsdom, and the sfdx-lwc-jest package supplies a transformer, a resolver, and stubs for platform imports. Platform imports resolve to stand-ins or to mocks you define in the test, so nothing contacts Salesforce.