Sub topic 15
Testing with Jest and base component stubs
This chapter assumes you can read a Lightning web component bundle, have Node.js and npm installed, and know the basics of Jest (describe, it, expect). The examples test the ContactSearch component from earlier chapters.
What a stub is
Jest runs in Node, not in a Salesforce org. The base components (lightning-*) are not available there, so the LWC Jest tooling replaces each one with a stub. A stub is a minimal component that has the same public attributes and events as the real one, but renders no internal markup.
In practice:
- You can set
value,labelordataon a stub and read it back. - You can dispatch events on a stub to simulate user actions.
- You cannot inspect what the real component would draw inside itself. The input's inner
<input>element and the datatable's rows do not exist in a test.
Test your component's behavior, meaning what it passes to base components and how it reacts to their events. Do not test the base components themselves.
Setup
Install the Salesforce Jest package in your project:
npm install @salesforce/sfdx-lwc-jest --save-devAdd a script to package.json:
{
"scripts": {
"test:unit": "sfdx-lwc-jest"
}
}The package supplies the lightning-* stubs and the transform that compiles LWC files. Put test files in a __tests__ folder inside the component bundle, named contactSearch.test.js. Run them with npm run test:unit.
Writing a test
This test covers the Clear button. It sets the input value, clicks Clear, and checks that the value resets.
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('clears the search text 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 Promise.resolve();
expect(input.value).toBe('Ada');
const button = element.shadowRoot.querySelector('lightning-button');
button.dispatchEvent(new CustomEvent('click'));
await Promise.resolve();
expect(input.value).toBe('');
});
});The steps are:
createElementbuilds the component, and appending it todocument.bodyruns it.element.shadowRoot.querySelectorfinds the stubs. Query the component's shadow root, notdocument.- Setting
input.valueand dispatchingchangerunshandleChange. It readsevent.target.value, which is the stub. await Promise.resolve()waits for the component to re-render. LWC updates the DOM asynchronously, so assertions made before the await see stale values.- The
afterEachcleanup removes elements so tests do not affect each other.
Passing data and events
The same approach works for the other components in this tutorial:
| Component | What to test |
|---|---|
| `lightning-datatable` | Set `data` and `columns` on the component under test, then assert that the stub's `data` equals what you expect. |
| `lightning-record-edit-form` | Dispatch a `success` event with a `detail` object and check your `handleSuccess` result. |
| `lightning-input` | Dispatch `change` and check the component's state or what it passes on. |
const table = element.shadowRoot.querySelector('lightning-datatable');
expect(table.data).toHaveLength(2);
expect(table.columns[0].fieldName).toBe('name');Common errors
- Assertion fails right after an event. You did not wait for the re-render. Add
await Promise.resolve(). querySelectorreturnsnull. You querieddocumentinstead ofelement.shadowRoot, or the element is inside a conditional block that is not yet rendered.- Tests affect each other. Elements from earlier tests are still in the DOM. Clean up in
afterEach.
Exercise
Why does the test above call await Promise.resolve() after dispatching the click event, and why can it not check the rendered text of the real lightning-input?
Show answer
LWC re-renders asynchronously, so the await lets the update finish before the assertion. In Jest, lightning-input is a stub with the same public attributes but no internal markup, so only its attributes and events can be tested.