Sub topic 15
Testing with Jest and base component stubs
This chapter covers unit testing Lightning web components that use base components. It assumes you know the structure of an LWC (template, class, CSS), have written the components from earlier chapters, and can run npm commands in a Salesforce DX project. Jest is the test runner, and @salesforce/sfdx-lwc-jest is the package that lets Jest understand LWC modules.
Why base components need stubs
Jest runs in Node.js with a simulated browser (jsdom). It does not run inside Salesforce. The base components such as lightning-input and lightning-card are implemented on the Salesforce platform, so they are not available in your local test run.
sfdx-lwc-jest solves this by replacing every lightning-* component with a stub. A stub is a small stand-in component that has the same tag name and the same public attributes, but only renders a simplified version of the real one. This has three consequences:
- Your component renders without errors, and you can query the stub elements.
- You can set and read public properties on a stub, such as
labelorvalue. - The stub does not reproduce internal behavior. A stubbed
lightning-inputdoes not validate input, and a stubbedlightning-datatabledoes not draw rows.
So a unit test checks what your component passes to a base component and how it reacts to the events the base component fires. It does not check how the base component looks.
Setting up Jest
A project created with the Salesforce CLI includes the setup. If you need to add it yourself, install the package and add a script.
npm install --save-dev @salesforce/sfdx-lwc-jestThen add scripts to package.json:
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest --watch",
"test:unit:coverage": "sfdx-lwc-jest --coverage"
}
}Tests live in a __tests__ folder inside the component's folder, and files end in .test.js.
force-app/main/default/lwc/contactSearch/
contactSearch.html
contactSearch.js
contactSearch.css
__tests__/
contactSearch.test.jsAnatomy of a component test
Every LWC test follows the same steps:
- Create the element with
createElementfromlwc. - Set public properties.
- Append the element to
document.body, which runsconnectedCallbackand renders. - Query the shadow DOM through
element.shadowRoot. - Assert, then clean up.
The test below uses the contactSearch component from the earlier chapter, with the lightning-input and the Clear button.
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
describe('c-contact-search', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders a search input with a label', () => {
const element = createElement('c-contact-search', {
is: ContactSearch
});
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
expect(input).not.toBeNull();
expect(input.label).toBe('Name');
expect(input.type).toBe('search');
});
});The afterEach block removes the elements so that one test cannot affect the next. Without it, leftover elements can cause confusing failures.
The assertions read input.label and input.type. These are the public properties you set in the template, and the stub exposes them.
Simulating events
To test behavior, dispatch the same events that the base component would fire. In the search component, the change event updates searchKey, and the Clear button resets it.
The stub does not fire change by itself, so the test creates and dispatches it. Because handleChange reads event.target.value, set the value on the stub before dispatching.
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
describe('c-contact-search events', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
async function flushPromises() {
return Promise.resolve();
}
it('updates the input value when the user types', async () => {
const element = createElement('c-contact-search', {
is: ContactSearch
});
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Ada';
input.dispatchEvent(new CustomEvent('change'));
await flushPromises();
expect(input.value).toBe('Ada');
});
it('clears the input when Clear is clicked', async () => {
const element = createElement('c-contact-search', {
is: ContactSearch
});
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Ada';
input.dispatchEvent(new CustomEvent('change'));
await flushPromises();
const button = element.shadowRoot.querySelector('lightning-button');
button.click();
await flushPromises();
expect(input.value).toBe('');
});
});The await matters. LWC re-renders asynchronously, in a microtask. If you assert immediately after changing state, the DOM still shows the old values. Awaiting a resolved promise lets the re-render finish first.
The Clear button is found with querySelector('lightning-button'). This works because the template has only one such button. With several, use a more specific selector, for example [data-id="clear"], and add a matching data-id attribute in the template.
Testing data passed to a datatable
A stubbed lightning-datatable keeps the data and columns properties you give it. You can check them without rendering rows. The test below uses the contactTable component from the datatable chapter.
import { createElement } from 'lwc';
import ContactTable from 'c/contactTable';
describe('c-contact-table', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('passes columns and rows to the datatable', () => {
const element = createElement('c-contact-table', {
is: ContactTable
});
document.body.appendChild(element);
const table = element.shadowRoot.querySelector('lightning-datatable');
expect(table.keyField).toBe('id');
expect(table.columns).toHaveLength(3);
expect(table.data).toHaveLength(2);
expect(table.data[0].name).toBe('Ada Lovelace');
});
});Notice that the HTML attribute key-field becomes the JavaScript property keyField. Attribute names with dashes are written in camelCase when you read them as properties.
To test a handler such as onrowselection, dispatch an event with the shape the real component sends:
table.dispatchEvent(
new CustomEvent('rowselection', {
detail: { selectedRows: [{ id: '1', name: 'Ada Lovelace' }] }
})
);Copy the detail shape from the base component documentation. If your test invents a different shape, it can pass while the real component fails.
Testing a record edit form
For lightning-record-edit-form, the useful checks are the attributes you set and your handler for onsuccess.
import { createElement } from 'lwc';
import ContactForm from 'c/contactForm';
describe('c-contact-form', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('binds the form to the Contact object and two fields', () => {
const element = createElement('c-contact-form', {
is: ContactForm
});
document.body.appendChild(element);
const form = element.shadowRoot.querySelector(
'lightning-record-edit-form'
);
expect(form.objectApiName).toBe('Contact');
const fields = element.shadowRoot.querySelectorAll(
'lightning-input-field'
);
const names = Array.from(fields).map((f) => f.fieldName);
expect(names).toEqual(['FirstName', 'LastName']);
});
});The stub does not save anything. You cannot check that a record was created from a unit test. You can only check that your component is configured correctly and that it reacts to the success event you dispatch yourself.
What the stubs do not cover
Knowing the limits prevents false confidence.
| Concern | Unit test with stubs | Where to test it |
|---|---|---|
| Attributes passed to a base component | Yes | Jest |
| Handler logic for events you dispatch | Yes | Jest |
| Rendered rows, validation messages, icons | No | Manual check or UI test |
| SLDS styling and styling hooks | No | Manual check in an org |
| Real record save through Lightning Data Service | No | Org or end-to-end test |
| Accessibility of the rendered result | Partly | Manual check and accessibility tools |
You can still check accessibility settings that are plain attributes. For example, assert that every lightning-input has a non-empty label, as the accessibility chapter recommends.
Common errors
- The element is
null. The selector does not match, or the markup is inside a child component's shadow DOM.querySelectoronly sees the shadow tree of the element you call it on. - An assertion sees the old value. You did not wait for the re-render. Add
await Promise.resolve()after the state change. - Tests affect each other. Elements were left in
document.body. Clean up inafterEach. - The handler throws on
event.target. Your test dispatched the event on a different element than the one the handler expects, or did not setvaluefirst. - Import of
c/componentNamefails. Jest cannot find the module. Check the component folder name and run the tests from the project root, wherejest.config.jslives.
Running the tests
Run all tests, one file, or in watch mode:
npm run test:unit
npm run test:unit -- contactSearch
npm run test:unit:watchUse the coverage script to see which lines of your component class were never run. Coverage shows untested code. It does not show whether the assertions are good.
Exercise
A test sets input.value = 'Ada', dispatches a change event on a stubbed lightning-input, and immediately asserts on text rendered from searchKey. The assertion fails although the handler is correct. What is the cause, and how do you fix it?
Show answer
LWC re-renders asynchronously in a microtask, so the DOM still shows the old value when the assertion runs. Make the test function async and add await Promise.resolve() after dispatching the event, then assert.
Exercise
Which of these can a Jest test with base component stubs check: (a) that lightning-datatable receives key-field="id", (b) that the datatable draws two rows, (c) that your onrowselection handler reads event.detail.selectedRows correctly?
Show answer
(a) and (c). The stub keeps the properties you set and lets you dispatch events yourself. (b) cannot be checked because the stub does not render rows.