Sub topic 3
Anatomy of a Jest test
This chapter assumes you can run npm run test:unit in a Salesforce DX project, as set up in the previous chapter. It also assumes you know basic JavaScript functions, arrow functions, and promises. You will learn how a Jest test file is organized, how hooks run, and which structural mistakes cause tests to pass or fail for the wrong reasons. The examples use plain JavaScript so that the Jest rules stand out. The next chapter applies them to Lightning web components.
Where test files live
Jest finds test files by name and location. By convention, a Lightning web component keeps its tests in a __tests__ folder inside the component bundle. Test files end in .test.js.
force-app/main/default/lwc/counter/
├── counter.html
├── counter.js
└── __tests__/
└── counter.test.jsThe __tests__ folder is not deployed to an org. Salesforce excludes it from the bundle, so tests do not count against deployment size.
The three building blocks
Every Jest test is built from three functions that Jest makes available globally. You do not import them.
describe(name, fn)groups related tests under a name.it(name, fn)defines one test.testis an alias with identical behavior.expect(value)starts an assertion about a value.
Here is a complete test file for a small function:
function total(prices) {
return prices.reduce((sum, price) => sum + price, 0);
}
describe('total', () => {
it('returns 0 for an empty list', () => {
expect(total([])).toBe(0);
});
it('adds up the prices', () => {
expect(total([1.5, 2.5])).toBe(4);
});
it('does not change the input array', () => {
const prices = [1, 2];
total(prices);
expect(prices).toEqual([1, 2]);
});
});A test passes if its function finishes without throwing. A failed expect throws an error, and that error is what Jest reports as a failure. A test with no assertions also passes, which is a common source of false confidence.
Test names read as a sentence together with their describe names: "total adds up the prices". Write names that state the behavior, not the implementation.
Arrange, act, assert
Inside each test, a three-step layout keeps the intent clear:
- Arrange: create the inputs and the object under test.
- Act: do the one thing you are testing.
- Assert: check the result.
Keep one behavior per test. When a test with six assertions fails, you have to work out which behavior broke. When a test with one focused assertion fails, the name tells you.
Matchers
The function you chain after expect(...) is called a matcher. These cover most LWC tests:
| Matcher | Checks | Typical use |
|---|---|---|
| `toBe(x)` | Same value or same reference (`Object.is`) | Strings, numbers, booleans |
| `toEqual(x)` | Same structure, compared recursively | Objects and arrays |
| `toBeTruthy()` / `toBeNull()` | Truthiness or exactly `null` | Checking that a query found an element |
| `toContain(x)` | Item in an array, or substring in a string | Rendered text |
| `toThrow()` | A function throws | Invalid input |
| `toHaveBeenCalledTimes(n)` | A mock function was called n times | Event handlers, Apex mocks |
| `toHaveBeenCalledWith(...)` | A mock was called with these arguments | Apex parameters |
Add .not before any matcher to invert it, for example expect(list).not.toContain('x').
The difference between toBe and toEqual matters often. expect({ a: 1 }).toBe({ a: 1 }) fails because the two objects are different references. toEqual passes because the contents match. For primitive values, use toBe.
Hooks: shared setup and cleanup
When several tests need the same setup, move it into a hook instead of copying it. Jest provides four:
beforeAll(fn)runs once before the first test in the block.beforeEach(fn)runs before every test in the block.afterEach(fn)runs after every test in the block.afterAll(fn)runs once after the last test in the block.
Hooks apply to the describe block that contains them, including nested blocks. The following file prints a line from each hook so you can see the order:
describe('outer', () => {
beforeAll(() => console.log('outer beforeAll'));
beforeEach(() => console.log('outer beforeEach'));
afterEach(() => console.log('outer afterEach'));
afterAll(() => console.log('outer afterAll'));
it('first', () => console.log(' test: first'));
describe('inner', () => {
beforeEach(() => console.log('inner beforeEach'));
afterEach(() => console.log('inner afterEach'));
it('second', () => console.log(' test: second'));
});
});The output order is:
- outer beforeAll
- outer beforeEach
- test: first
- outer afterEach
- outer beforeEach
- inner beforeEach
- test: second
- inner afterEach
- outer afterEach
- outer afterAll
Before a test, hooks run from the outside in. After a test, they run from the inside out.
Choosing between beforeEach and beforeAll
Use beforeEach for anything a test can change. In LWC tests, that includes every component you create and every mock you configure. Use beforeAll only for expensive, read-only setup. If a test mutates something created in beforeAll, the next test sees the changed state, and the result depends on test order.
State shared between tests
Variables declared at the top of a describe block are shared by all its tests. This pattern is safe because beforeEach replaces the value each time:
describe('shopping list', () => {
let list;
beforeEach(() => {
list = ['milk'];
});
it('adds an item', () => {
list.push('eggs');
expect(list).toEqual(['milk', 'eggs']);
});
it('starts with one item', () => {
expect(list).toHaveLength(1);
});
});If you wrote const list = ['milk']; directly in the describe body, the second test would fail, because the first test already added 'eggs' to the same array. Jest runs tests in the order they are defined, but you should never rely on that. Each test should pass when run alone.
The same rule applies to the DOM in LWC tests. Components you attach to document.body persist across tests in a file unless you remove them. A later chapter covers that cleanup in detail, and it belongs in an afterEach hook.
Async tests
Jest waits for a test to finish only if it knows the test is asynchronous. There are two reliable ways to tell it: return a promise, or declare the function async and use await.
function loadName() {
return Promise.resolve('Ada');
}
describe('loadName', () => {
it('resolves with the name', async () => {
const name = await loadName();
expect(name).toBe('Ada');
});
it('can also use resolves', async () => {
await expect(loadName()).resolves.toBe('Ada');
});
});Hooks can be async in the same way. Only the functions passed to it and the hooks may be async. Do not make the callback of describe async: Jest does not wait for it, and tests defined after an await are not registered.
Mock functions in the structure
A mock function, created with jest.fn(), records how it was called. It lets you assert on collaborators such as event handlers.
describe('jest.fn', () => {
it('records calls', () => {
const handler = jest.fn();
handler('a');
handler('b');
expect(handler).toHaveBeenCalledTimes(2);
expect(handler).toHaveBeenLastCalledWith('b');
});
});Mocks keep their call history until you clear it. A mock defined at module level and used in several tests accumulates calls. Reset it in beforeEach or afterEach with jest.clearAllMocks(). That function clears call history but keeps any implementation you set, such as mockResolvedValue. jest.resetAllMocks() removes the implementations as well.
Running a subset of tests
While you work on one test, you can narrow the run:
it.only(...)ordescribe.only(...)runs only that test or block within the file.it.skip(...)skips a test and reports it as skipped.npm run test:unit -- -t "adds up"runs only tests whose full name matches the text.npm run test:unit -- path/to/file.test.jsruns one file.
Common structural mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| A test passes but checks nothing | No `expect`, or an un-awaited promise | Await every promise and add an assertion |
| A test passes alone but fails in the full run | State leaks from an earlier test | Reset state in `beforeEach` or `afterEach` |
| `toBe` fails on objects that look equal | Reference comparison | Use `toEqual` |
| A mock reports too many calls | Call history carried over from earlier tests | Call `jest.clearAllMocks()` in a hook |
| Tests are missing from the report | `.only` on another test, or an async `describe` | Remove `.only`, and make the `describe` callback synchronous |
Exercise
A file declares const items = []; inside a describe block, with no hooks. Test A pushes 'x' into items and asserts its length is 1. Test B, defined after A, asserts that items has length 0. Test B fails. Why does it fail, and how do you fix it?
Show answer
Both tests share the same array. Test A mutates it, so it still contains 'x' when test B runs. Declare let items; in the describe block and assign items = []; in a beforeEach hook, so each test starts with a fresh array.
Exercise
In a describe block with a beforeEach hook, a nested describe also has a beforeEach hook. In what order do the two hooks run before a test in the nested block, and in what order do the matching afterEach hooks run afterward?
Show answer
Before the test, the outer beforeEach runs first and the inner one runs second. After the test, the inner afterEach runs first and the outer one runs second.