Sub topic 13
The `__tests__` Folder and Jest
This chapter assumes you can read a component bundle (HTML, JavaScript and js-meta.xml files), know basic JavaScript modules and Promises, and have Node.js and npm installed. You don't need prior Jest experience.
What the folder is for
A bundle can hold a folder named __tests__. It holds Jest test files that check the component's behavior without a Salesforce org. Jest is a JavaScript test runner. It runs in Node.js and uses jsdom, a simulated browser DOM, so tests run in seconds on your machine.
force-app/main/default/lwc/
└── greetingCard/
├── greetingCard.html
├── greetingCard.js
├── greetingCard.js-meta.xml
└── __tests__/
└── greetingCard.test.jsThree rules apply to the folder:
- It must be named
__tests__, with two underscores on each side, and sit directly inside the bundle folder. - Test files end in
.test.js(or.spec.js). Jest's default matching finds them by that suffix. - The folder stays in source control but is not deployed. The platform ignores it, so tests never count toward your org's code size.
The test file's base name does not have to match the bundle name, but greetingCard.test.js is the convention. It makes the file easy to find.
Setting up Jest
Salesforce provides @salesforce/sfdx-lwc-jest, a package that bundles Jest with the transforms and resolvers an LWC needs. Install it once per project:
npm install @salesforce/sfdx-lwc-jest --save-devProjects created from the standard Salesforce DX template already include a jest.config.js and a package.json script. If you add them yourself, they look like this:
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}The configuration does two jobs. It compiles LWC templates and decorators such as @api so Node can load them. It also maps c/greetingCard style imports to the matching bundle folders, so a test imports a component the way another component would.
Run all tests with npm run test:unit. To run one file, pass its path after --, for example npm run test:unit -- greetingCard.
Anatomy of a component test
Here is the test from the greetingCard bundle:
import { createElement } from 'lwc';
import GreetingCard from 'c/greetingCard';
describe('c-greeting-card', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the name', () => {
const element = createElement('c-greeting-card', { is: GreetingCard });
element.name = 'Ada';
document.body.appendChild(element);
return Promise.resolve().then(() => {
const p = element.shadowRoot.querySelector('p');
expect(p.textContent).toBe('Hello, Ada!');
});
});
});Each part has a purpose:
createElementbuilds an instance of the component. The first argument is the tag name (the folder name in kebab case with ac-prefix). Theisoption takes the class you imported.- Setting
element.nameworks becausenameis an@apiproperty. Private fields are not reachable from the test, which is intentional. Test through the public surface. document.body.appendChildconnects the component.connectedCallbackruns and the first render happens at that point.Promise.resolve().then(...)waits one microtask. LWC re-renders asynchronously, so a DOM check straight after a property change can see stale markup.element.shadowRoot.querySelectorreads the rendered output. In tests the shadow root is open, so you can query inside it, which is not possible from outside code in a real org.afterEachremoves elements so one test's DOM does not leak into the next.
Testing events and user actions
Components talk to parents with events. A test listens on the element it created. Suppose a counterButton component dispatches a countchange event when its button is clicked:
// counterButton.js
import { LightningElement } from 'lwc';
export default class CounterButton extends LightningElement {
count = 0;
handleClick() {
this.count += 1;
this.dispatchEvent(
new CustomEvent('countchange', { detail: this.count })
);
}
}<template>
<button onclick={handleClick}>Clicked {count} times</button>
</template>// __tests__/counterButton.test.js
import { createElement } from 'lwc';
import CounterButton from 'c/counterButton';
describe('c-counter-button', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('fires countchange and updates the label', async () => {
const element = createElement('c-counter-button', { is: CounterButton });
const handler = jest.fn();
element.addEventListener('countchange', handler);
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail).toBe(1);
expect(element.shadowRoot.querySelector('button').textContent).toBe(
'Clicked 1 times'
);
});
});The async and await Promise.resolve() form does the same job as the .then chain and reads more simply. The event check itself needs no waiting because dispatchEvent is synchronous. The label check does need it, because the re-render is deferred.
Mocking what Jest cannot run
Jest has no org behind it, so anything that calls the platform must be replaced. Common cases:
| Dependency | How tests handle it |
|---|---|
| Base components such as `lightning-card` | `sfdx-lwc-jest` supplies stub versions automatically, so markup renders but the platform behavior does not |
| Apex methods (`@salesforce/apex/...`) | Mock the import with `jest.mock` and control its return value |
| `@wire` adapters | Use the test adapters from `@salesforce/sfdx-lwc-jest` and call `emit()` with sample data |
| Schema and user imports (`@salesforce/schema/...`, `@salesforce/user/Id`) | Resolved to simple stand-in values by the config |
| Child components in your own namespace | Real by default. Use `jest.mock` only if you need to replace one |
A mock for an imperative Apex call looks like this:
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
it('shows contacts returned by Apex', async () => {
getContacts.mockResolvedValue([{ Id: '003xx', Name: 'Ada Lovelace' }]);
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await Promise.resolve();
expect(getContacts).toHaveBeenCalled();
});The virtual: true option tells Jest the module does not exist on disk. The import path is a platform-provided name, not a file.
Common errors
- "Cannot find module 'c/...'": the config is missing or does not spread
jestConfig, so thec/mapping is absent. Checkjest.config.js. - No tests found: the folder is misspelled (
_tests_,tests) or the file does not end in.test.js. - Assertions see old markup: the test did not wait for the re-render. Wait a microtask after every property change or user action.
- Element is empty or
shadowRootqueries returnnull: the element was never appended todocument.body, so it never rendered. - Tests affect each other: no
afterEachcleanup, or shared state in module-level variables. - Deploy complains about the folder: this is rare. If a custom script copies the bundle by hand, exclude
__tests__. Standardsf project deploytooling skips it.
Where tests fit when choosing files
Of all the optional files in a bundle, the __tests__ folder is the only one that has no effect on what the component does in the org. It is there for the developers. Add it whenever a component has logic that can break: conditional rendering, event handling, data loading. For a purely static template, you can reasonably skip it. Many teams require tests on every component, though, and run test:unit:coverage in continuous integration to enforce a minimum.
Exercise
A teammate writes element.name = 'Grace'; in a test, appends the element to document.body, then immediately runs expect(element.shadowRoot.querySelector('p').textContent).toBe('Hello, Grace!'). The assertion fails with the old text, even though the component is correct. Wait: the property was set before appendChild. What is a more likely cause if the property is changed after the element is appended, and how do you fix it?
Show answer
If the property is set after the element is connected, LWC schedules the re-render for a later microtask, so the DOM still shows the old value when the assertion runs. Fix it by returning a Promise or awaiting Promise.resolve() after the change and before reading the DOM. When the property is set before appendChild, the first render already uses the new value, so no wait is needed.
Exercise
You added __tests__/loginPanel.test.js but npm run test:unit reports "No tests found". Name two things to check.
Show answer
Check that the folder is named exactly __tests__ (two underscores on each side) and sits directly inside the bundle folder. Check that the file name ends in .test.js or .spec.js. Also confirm the test:unit script and jest.config.js exist in the project root.