| | |

Jest 04 ๐Ÿƒ Test Structure โ€” describe, it, and the Arrange-Act-Assert Pattern

โฑ๏ธ Estimated read: 9 min | |

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

FunctionRunsScope
describe(name, fn)Once at collectionGroups tests
beforeAll(fn)Once per blockOutermost-first
beforeEach(fn)Before every testOutermost-first
afterEach(fn)After every testInnermost-first
afterAll(fn)Once per blockInnermost-first

The Three Phases

PhasePurposeExample
ArrangeSet up preconditionsCreate the object, seed the data
ActPerform the operationCall the method
AssertCheck the outcomeexpect(result).toBe(...)

Naming

LevelConvention
describeUnit or scenario
itBehavior, completes “it …”
Full nameSpace-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

PitfallWhy It HappensFix
Tests pass alone, fail togetherShared mutable stateReset in beforeEach
Setup runs more than expectedbeforeEach vs beforeAll confusionUse beforeAll for shared, beforeEach for per-test
Hook order wrongAssumed inner-first for beforeEachOutermost-first before, innermost-first after
Failure is hard to diagnoseInterleaved actions and assertionsOne 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

ItemValue
Groupingdescribe(name, fn)
Test caseit(name, fn) / test(name, fn)
Per-test setupbeforeEach (outermost-first)
Per-suite setupbeforeAll (once per block)
Per-test teardownafterEach (innermost-first)
Case structureArrange, Act, Assert
Full nameSpace-separated in reporter

Key takeaways:

  • describe groups 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. beforeEach runs outermost-first, afterEach runs innermost-first. A hook that depends on another’s side effect must be declared after it in the same block.
  • beforeAll is for shared setup; beforeEach is 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.

Was this helpful?


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!