Sub topic 3
Anatomy of a Jest test
This chapter assumes you can read basic Lightning web component code, know JavaScript promises and async/await, and have a Salesforce DX project with @salesforce/sfdx-lwc-jest installed as described in the previous chapter. Here you learn how a Jest test file is organized. Later chapters apply this structure to real components.
Where test files live
By default, Jest finds files that end in .test.js or .spec.js. For Lightning web components, the convention is to put them in a __tests__ folder inside the component's own folder:
force-app/main/default/lwc/counter/
counter.html
counter.js
__tests__/
counter.test.jsThe __tests__ folder is not deployed to an org, so tests stay out of your package.
The four building blocks
A Jest test file is built from a few functions that Jest provides as globals. You do not import them.
| Function | Purpose |
|---|---|
| `describe(name, fn)` | Groups related tests under one name. |
| `it(name, fn)` | Defines one test. `test` is an alias. |
| `expect(value)` | Starts an assertion about a value. |
| `beforeEach`, `afterEach` | Run code before or after every test in the group. |
An assertion pairs expect with a matcher. A matcher is a method such as toBe, toEqual, toContain, or toHaveBeenCalledTimes that checks the value.
describe('arithmetic', () => {
it('adds two numbers', () => {
expect(1 + 1).toBe(2);
});
it('compares objects by value', () => {
expect({ a: 1 }).toEqual({ a: 1 });
});
});Use toBe for primitives and identity. Use toEqual when you compare the contents of objects or arrays. toBe on two separate but identical objects fails, which is a common first error.
Arrange, act, assert
Write each test in three steps:
- Arrange. Create the component and set its starting state.
- Act. Do the thing you want to test, such as a click.
- Assert. Check the result with
expect.
Keep each it focused on one behavior. When a test fails, its name should tell you what broke.
Hooks control setup and cleanup
Hooks remove repeated code. beforeEach runs before each test, and afterEach runs after each test. Two more, beforeAll and afterAll, run once per describe block.
describe('hooks', () => {
beforeEach(() => {
console.log('before each test');
});
afterEach(() => {
console.log('after each test');
});
it('first', () => {
expect(true).toBe(true);
});
it('second', () => {
expect(true).toBe(true);
});
});Prefer beforeEach and afterEach over beforeAll and afterAll. Shared state set up once can leak between tests and make results depend on run order.
Async tests
A test that waits for a promise must tell Jest to wait too. Mark the function async and use await. Without it, Jest finishes the test before the promise settles, and a failing assertion may never be reported.
describe('async test', () => {
it('waits for a promise', async () => {
const value = await Promise.resolve(42);
expect(value).toBe(42);
});
});LWC tests wait this way for re-rendering, which a later chapter covers.
A complete test file
This file combines all the pieces for the counter component from earlier chapters. Rendering with createElement is explained in the next chapter. For now, focus on the structure.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
let element;
beforeEach(() => {
element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
});
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('starts at zero', () => {
const count = element.shadowRoot.querySelector('.count');
expect(count.textContent).toBe('0');
});
it('adds one after a click', async () => {
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
const count = element.shadowRoot.querySelector('.count');
expect(count.textContent).toBe('1');
});
});The describe names the component. Each it reads as a sentence. The hooks create a fresh component for every test and remove it afterward.
Common errors
- Forgetting
await. The test passes even though an assertion would fail later. - Using
toBeon objects. UsetoEqualfor contents. - Sharing state across tests. Create what you need in
beforeEachinstead of at the top of the file. - Vague test names.
it('works')tells you nothing when it fails.
Exercise
In the complete test file, why is the component created in beforeEach instead of once at the top of the describe block?
Show answer
Each test needs a fresh component with its starting state. Creating it in beforeEach, and removing it in afterEach, stops one test's clicks or property changes from affecting the next test, so results do not depend on run order.
Exercise
A test clicks a button, then calls expect on the rendered text without using await. The test passes, but the text on screen is wrong. What is the likely cause and the fix?
Show answer
The assertion ran before the component re-rendered, or Jest ended the test before a later check ran. Make the test function async and await a promise, such as await Promise.resolve(), after the click and before asserting.