Jest 04 ๐ Test Structure โ describe, it, and the Arrange-Act-Assert Pattern
A Jest test suite is a tree of describe blocks containing it cases. The describe block names a group, scopes the hooks that run around the tests, and appears in the reporter’s output as a prefix on every test name. Inside the case, the body is conventionally organized into three phases: arrange the preconditions, act on the subject under test, assert the expected outcome. The three-phase pattern is not enforced by Jestโthe framework only sees a function that either returns or throwsโbut it is the structure that makes a test readable, and the structure that the failure message reflects when a test breaks.
This chapter covers the describe/it tree, the hook scoping that determines setup and teardown order, and the Arrange-Act-Assert pattern that separates the three phases of a test case. The sections that follow walk through grouping, hooks, and the case structure that keeps a suite navigable.
Key point: describe groups and scopes hooks; beforeEach runs outermost-first and afterEach runs innermost-first; inside each it, the Arrange-Act-Assert split keeps the setup, the action, and the assertion visually distinct so a failure points at the phase that broke.
a. The describe/it tree and hook scoping
describe(name, fn) declares a suite. The callback runs immediately during collection, and the test calls inside it register the cases. The full name of a test in the reporter is the concatenation of every enclosing describe name plus the test name, separated by a space in Jest (not > as in Vitest). The nesting is for organization and for hook scoping.
describe("user service", () => {
describe("create", () => {
it("returns the created user", () => {
expect(createUser({ name: "Ana" })).toMatchObject({ name: "Ana" });
});
it("rejects a missing name", () => {
expect(() => createUser({})).toThrow("name is required");
});
});
describe("delete", () => {
it("removes the user", () => {
deleteUser("1");
expect(findUser("1")).toBeUndefined();
});
});
});
The hooks scope to the block that contains them. beforeEach runs before every test in the block and in every nested block; afterEach runs after every test. The execution order is outermost-first for beforeEach and innermost-first for afterEach. beforeAll and afterAll run once per block, which is where expensive setup belongs.
describe("outer", () => {
beforeAll(() => console.log("outer beforeAll"));
beforeEach(() => console.log("outer beforeEach"));
afterEach(() => console.log("outer afterEach"));
afterAll(() => console.log("outer afterAll"));
describe("inner", () => {
beforeEach(() => console.log("inner beforeEach"));
afterEach(() => console.log("inner afterEach"));
it("runs", () => console.log("test"));
});
});
// Order:
// outer beforeAll
// outer beforeEach
// inner beforeEach
// test
// inner afterEach
// outer afterEach
// outer afterAll
The most common hook mistake is sharing mutable state across tests without resetting it. A module-level array that a test pushes into leaks into the next test, and the failure appears only when the suite runs as a whole. The fix is to reset the state in beforeEach, not to add beforeAll setup that only runs once.
b. The Arrange-Act-Assert pattern
The three-phase pattern is a convention for the body of a single it. Arrange sets up the objects and the state the test needs. Act performs the operation under test. Assert checks the result. The phases are separated by blank lines so that a reader can see where the setup ends and the action begins.
it("applies a discount to the total", () => {
// Arrange
const cart = new Cart();
cart.add({ price: 100, qty: 1 });
const discount = { percent: 10 };
// Act
const total = cart.total(discount);
// Assert
expect(total).toBe(90);
});
The pattern’s value is diagnostic. When the test fails, the failure message points at the assertion, but the reader can see whether the cause is the setup (the cart was not what the test assumed) or the action (the method returned the wrong value). A test that mixes the phasesโan assertion in the middle of setup, a second action after the first assertionโis harder to diagnose because the failure could be in any of the interleaved steps.
The pattern also discourages a common anti-pattern: the “act-assert-act-assert” test that performs several operations and asserts after each. That test is really several tests, and splitting it makes each failure attributable to one behavior.
// BAD: multiple actions and assertions in one test
it("handles the cart", () => {
const cart = new Cart();
cart.add({ price: 10 });
expect(cart.total()).toBe(10);
cart.add({ price: 20 });
expect(cart.total()).toBe(30);
cart.remove(0);
expect(cart.total()).toBe(20);
});
// GOOD: one behavior per test
it("adds an item to the total", () => {
const cart = new Cart();
cart.add({ price: 10 });
expect(cart.total()).toBe(10);
});
it("adds a second item to the total", () => {
const cart = new Cart();
cart.add({ price: 10 });
cart.add({ price: 20 });
expect(cart.total()).toBe(30);
});
The trade-off is more test cases with more setup. The beforeEach hook mitigates the setup duplication: the cart is created in beforeEach, and each test only performs the actions relevant to its behavior.
c. Naming and the reporter output
The test name should describe the behavior, not the implementation. it("returns the sum") survives a refactor of the internal helper; it("calls _add") breaks when the helper is renamed. The describe name should name the unit or the scenario, and the it name should complete the sentence “it …”.
The reporter output shows the full path to the failing test. A failure in the user service > create > rejects a missing name test tells the reader which unit, which method, and which behavior failed without opening the file. The full name is what appears in CI logs and in the editor’s test explorer, which is why the naming is not cosmetic.
The failure message also includes the line of the failing assertion and a diff of the expected and received values. A test that asserts on a large object produces a diff that shows only the differing fields, which is the reason toEqual and toMatchObject are preferred over toBe for objects.
Complete Example Session
// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/cart.js
class Cart {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
total() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
}
module.exports = { Cart };
// ============================================
// PART 2: THE SUITE
// ============================================
// src/cart.test.js
const { Cart } = require("./cart");
describe("Cart", () => {
let cart;
beforeEach(() => {
// Fresh state for every test
cart = new Cart();
});
describe("add", () => {
it("adds an item to the cart", () => {
// Arrange
const item = { price: 10, qty: 1 };
// Act
cart.add(item);
// Assert
expect(cart.items).toHaveLength(1);
});
});
describe("total", () => {
it("returns 0 for an empty cart", () => {
expect(cart.total()).toBe(0);
});
it("sums price times quantity", () => {
// Arrange
cart.add({ price: 10, qty: 2 });
cart.add({ price: 5, qty: 1 });
// Act
const total = cart.total();
// Assert
expect(total).toBe(25);
});
});
});
// ============================================
// PART 3: THE REPORTER OUTPUT
// ============================================
// PASS src/cart.test.js
// Cart
// add
// โ adds an item to the cart
// total
// โ returns 0 for an empty cart
// โ sums price times quantity
The parts covered the module, the beforeEach reset, the Arrange-Act-Assert split, and the reporter output that shows the full test path.
Quick Reference
Grouping and Hooks
| Function | Runs | Scope |
|---|---|---|
describe(name, fn) | Once at collection | Groups tests |
beforeAll(fn) | Once per block | Outermost-first |
beforeEach(fn) | Before every test | Outermost-first |
afterEach(fn) | After every test | Innermost-first |
afterAll(fn) | Once per block | Innermost-first |
The Three Phases
| Phase | Purpose | Example |
|---|---|---|
| Arrange | Set up preconditions | Create the object, seed the data |
| Act | Perform the operation | Call the method |
| Assert | Check the outcome | expect(result).toBe(...) |
Naming
| Level | Convention |
|---|---|
describe | Unit or scenario |
it | Behavior, completes “it …” |
| Full name | Space-separated in reporter |
Best Practices
โ Do This:
// Fresh state in beforeEach
beforeEach(() => { cart = new Cart(); }); // โ
// Separate the three phases with blank lines
const total = cart.total(); // act // โ
expect(total).toBe(25); // assert // โ
// Name the behavior
it("returns 0 for an empty cart", ...) // โ
โ Don’t Do This:
// Share mutable state without reset
const cart = new Cart(); // module-level // โ
// Interleave actions and assertions
cart.add(a); expect(cart.total()).toBe(1); cart.add(b); // โ
// Name the implementation
it("calls _calculateTotal", ...) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Tests pass alone, fail together | Shared mutable state | Reset in beforeEach |
| Setup runs more than expected | beforeEach vs beforeAll confusion | Use beforeAll for shared, beforeEach for per-test |
| Hook order wrong | Assumed inner-first for beforeEach | Outermost-first before, innermost-first after |
| Failure is hard to diagnose | Interleaved actions and assertions | One behavior per test, three phases |
Real-World Examples
1. Basic group
describe("math", () => { it("adds", () => { ... }); });
2. Nested groups
describe("math", () => { describe("add", () => { ... }); });
3. Reset in beforeEach
beforeEach(() => { cart = new Cart(); });
4. Shared setup in beforeAll
beforeAll(async () => { db = await connect(); });
5. Arrange-Act-Assert
const item = { price: 10, qty: 1 }; // arrange
cart.add(item); // act
expect(cart.items).toHaveLength(1); // assert
6. Async hook
beforeEach(async () => { await db.clear(); });
7. Cleanup in afterEach
afterEach(() => { jest.restoreAllMocks(); });
8. One behavior per test
it("returns 0 for empty", ...);
it("sums items", ...);
9. Distinct names
it("adds an item", ...);
it("removes an item", ...);
10. Full name
Cart > total > sums price times quantity
Visual
Hook Execution Order
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ outer describe โ
โ beforeAll (1) โ
โ beforeEach (2) โ
โ โ
โ inner describe โ
โ beforeEach (3) โ
โ it (4) โ
โ afterEach (5) โ
โ โ
โ afterEach (6) โ
โ afterAll (7) โ
โ โ
โ before: outermost-first โ
โ after: innermost-first โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Arrange-Act-Assert
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ it("sums price times quantity", () => { โ
โ // Arrange โ
โ cart.add({ price: 10, qty: 2 }); โ
โ cart.add({ price: 5, qty: 1 }); โ
โ โ
โ // Act โ
โ const total = cart.total(); โ
โ โ
โ // Assert โ
โ expect(total).toBe(25); โ
โ }); โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Reporter Output
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PASS src/cart.test.js โ
โ Cart โ
โ add โ
โ โ adds an item to the cart โ
โ total โ
โ โ returns 0 for an empty cart โ
โ โ sums price times quantity โ
โ โ
โ Full name = describe chain + it name โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
State Reset
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WITHOUT beforeEach โ
โ Test 1: cart has 1 item โ
โ Test 2: cart has 2 items (leaked) โ FAIL โ
โ โ
โ WITH beforeEach โ
โ Test 1: fresh cart, 1 item โ
โ Test 2: fresh cart, 0 items โ passes โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Grouping | describe(name, fn) |
| Test case | it(name, fn) / test(name, fn) |
| Per-test setup | beforeEach (outermost-first) |
| Per-suite setup | beforeAll (once per block) |
| Per-test teardown | afterEach (innermost-first) |
| Case structure | Arrange, Act, Assert |
| Full name | Space-separated in reporter |
Key takeaways:
describegroups and scopes; it is not cosmetic. The block’s name appears in every test’s full name, and the hooks declared inside it apply only to the tests within it.- Hook order is directional.
beforeEachruns outermost-first,afterEachruns innermost-first. A hook that depends on another’s side effect must be declared after it in the same block. beforeAllis for shared setup;beforeEachis for per-test state. Mutable state shared across tests leaks between them and produces failures that appear only when the suite runs as a whole.- Arrange-Act-Assert separates the phases. The blank lines between setup, action, and assertion make the failure diagnosable: the reader can see whether the setup was wrong or the action returned the wrong value.
- One behavior per test. A test with multiple actions and assertions is really several tests, and splitting it makes each failure attributable to one behavior.
Remember: A test suite is a document that describes what the code does. describe names the unit, it names the behavior, and the hooks set up the state. Inside the case, the Arrange-Act-Assert split keeps the setup, the action, and the assertion distinct. When a test passes alone but fails in the suite, the cause is shared mutable state; when the failure is hard to diagnose, the cause is interleaved phases. Reset in beforeEach, name the behavior, and keep one behavior per test.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!