Vitest 04 🧪 Test Structure — describe, it, and Organizing Suites
A single test file with ten flat test calls is readable until it grows to fifty. The structure that keeps a suite navigable is describe, the grouping function that names a block of tests and scopes the hooks that run around them. describe is not cosmetic: it determines the order in which beforeEach and afterEach hooks execute, the nesting depth of the test names in the reporter output, and the context available to the tests inside the block. A suite organized around behavior, not implementation, uses describe to name the unit and it to name the case.
This chapter covers the describe block, the nesting rules, the hooks that scope to it, and the organizational patterns that keep large suites maintainable. The sections that follow walk through grouping, hook scoping, and the structural conventions that make failures easy to locate.
Key point: describe groups tests and scopes hooks; hooks run outermost-first before and innermost-first after, and a test’s full name in the reporter is the concatenation of every enclosing describe name plus the it name.
a. Grouping and naming
describe(name, fn) declares a suite. The fn runs immediately during collection, and the test calls inside it register the cases. Nested describe blocks create nested suites, and the full name of a test is built from the chain of names.
import { describe, it, expect } from "vitest";
import { add, divide } from "./math";
describe("math", () => {
describe("add", () => {
it("returns the sum of two positives", () => {
expect(add(1, 2)).toBe(3);
});
it("handles negatives", () => {
expect(add(-1, -2)).toBe(-3);
});
});
describe("divide", () => {
it("divides two numbers", () => {
expect(divide(10, 2)).toBe(5);
});
it("throws on division by zero", () => {
expect(() => divide(1, 0)).toThrow("Division by zero");
});
});
});
The reporter displays the full name as math > add > returns the sum of two positives. The > separator is the default in Vitest; the space separator in Jest is a documented difference. The full name is what appears in CI logs, editor test explorers, and failure messages, which is why the names should describe behavior rather than implementation. A test named calls the internal helper breaks when the helper is renamed; a test named returns the sum survives the refactor.
The nesting depth should follow the domain, not the file tree. Two levels—unit and behavior—is usually enough. A third level for edge cases is acceptable; a fourth is a sign that the suite is testing too much at once.
b. Hook scoping and execution order
The hooks beforeAll, beforeEach, afterEach, and afterAll scope to the describe 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.
import { describe, it, beforeEach, afterEach, beforeAll, afterAll } from "vitest";
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"));
});
});
// Output order:
// outer beforeAll
// outer beforeEach
// inner beforeEach
// test
// inner afterEach
// outer afterEach
// outer afterAll
The beforeAll and afterAll hooks run once per describe block, not once per test. They are for expensive setup—starting a database connection, launching a server—that every test in the block shares. The beforeEach and afterEach hooks run around every test and are for per-test state that must be reset.
The hooks run in the order they are declared within the same block. Two beforeEach calls in the same describe run in declaration order; the afterEach calls run in reverse declaration order. This matters when one hook depends on another’s side effect.
c. Organizational patterns for large suites
Three patterns cover most real suites. The choice depends on what varies between tests.
Flat cases inside one describe work when the unit has a small number of behaviors and no shared setup. The describe names the unit; each it names one behavior.
Nested describe per method or scenario works when a class or module has multiple methods with distinct behaviors. The outer describe names the unit, the inner describe names the method, and the it names the case. This is the pattern in the previous section.
Table-driven tests work when the same assertion runs against many inputs. A describe.each or it.each block generates one test per row, and the row’s name appears in the test name. Vitest’s each is the replacement for the repetitive test calls that share a body.
import { describe, it, expect } from "vitest";
describe("parsePort", () => {
it.each([
["80", 80],
["443", 443],
["8080", 8080],
])("parses %s to %i", (input, expected) => {
expect(parsePort(input)).toBe(expected);
});
it.each([
["-1", "Port must be positive"],
["99999", "Port must be below 65536"],
["abc", "Port must be numeric"],
])("rejects %s", (input, message) => {
expect(() => parsePort(input)).toThrow(message);
});
});
The %s and %i placeholders in the name are filled from the row’s values, so each generated test has a distinct name in the reporter. The describe.each variant runs the whole block for each row, which is useful when the row’s value is shared across several tests.
The suite should also declare its mocks and fixtures at the top of the file, not inside the it body. A vi.mock() call is hoisted to the top of the file regardless of where it is written, but the vi.hoisted() variables and the shared fixtures are clearer when they are at the file scope and reset in beforeEach.
Complete Example Session
// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/cart.ts
export type Item = { id: string; price: number; qty: number };
export function total(items: Item[]): number {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
export function addItem(items: Item[], item: Item): Item[] {
const existing = items.find((i) => i.id === item.id);
if (existing) {
return items.map((i) =>
i.id === item.id ? { ...i, qty: i.qty + item.qty } : i
);
}
return [...items, item];
}
// ============================================
// PART 2: THE SUITE
// ============================================
// src/cart.test.ts
import { describe, it, expect, beforeEach } from "vitest";
import { total, addItem, type Item } from "./cart";
describe("cart", () => {
let items: Item[];
beforeEach(() => {
// Fresh state for every test
items = [{ id: "a", price: 10, qty: 2 }];
});
describe("total", () => {
it("sums price times quantity", () => {
expect(total(items)).toBe(20);
});
it("returns 0 for an empty cart", () => {
expect(total([])).toBe(0);
});
it.each([
[[{ id: "a", price: 10, qty: 1 }], 10],
[[{ id: "a", price: 10, qty: 3 }], 30],
])("total of %o is %i", (input, expected) => {
expect(total(input)).toBe(expected);
});
});
describe("addItem", () => {
it("appends a new item", () => {
const result = addItem(items, { id: "b", price: 5, qty: 1 });
expect(result).toHaveLength(2);
});
it("increments quantity of an existing item", () => {
const result = addItem(items, { id: "a", price: 10, qty: 1 });
expect(result[0].qty).toBe(3);
});
it("does not mutate the original array", () => {
addItem(items, { id: "b", price: 5, qty: 1 });
expect(items).toHaveLength(1);
});
});
});
The parts covered the module, the fresh-state hook, the describe per function, the table-driven tests, and the immutability test that would fail if addItem mutated its input.
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 |
Parameterized Tests
| Form | Generates |
|---|---|
it.each(rows)(name, fn) | One test per row |
describe.each(rows)(name, fn) | One block per row |
%s, %i, %o, %j | Name placeholders |
Naming
| Level | Convention |
|---|---|
Outer describe | Unit or module name |
Inner describe | Method or scenario |
it | Behavior in plain language |
| Full name | Joined by > in reporter |
Best Practices
✅ Do This:
// Name the behavior, not the implementation
it("increments quantity of an existing item", ...) // ✅
// Reset state in beforeEach
beforeEach(() => { items = [initial]; }); // ✅
// Use each for repeated assertions
it.each([[1, 1], [2, 4]])("square of %i is %i", ...) // ✅
// Scope expensive setup with beforeAll
beforeAll(async () => { db = await connect(); }); // ✅
❌ Don’t Do This:
// Share mutable state across tests without reset
const items = []; // module-level, leaks between tests // ❌
// Nest too deep
describe("a", () => describe("b", () => describe("c", ...))) // ❌
// Use implementation names in test names
it("calls _internalHelper", ...) // ❌
// Use beforeAll for per-test state
beforeAll(() => { user = createUser(); }); // ❌
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 |
| Duplicate test names | Same it name in sibling blocks | Use distinct names or each |
Real-World Examples
1. Basic group
describe("math", () => { it("adds", () => { ... }); });
2. Nested groups
describe("math", () => { describe("add", () => { ... }); });
3. Reset in beforeEach
beforeEach(() => { items = []; });
4. Shared setup in beforeAll
beforeAll(async () => { db = await connect(); });
5. Table-driven test
it.each([[1, 2, 3], [2, 3, 5]])("%i + %i = %i", (a, b, c) => {
expect(add(a, b)).toBe(c);
});
6. Table-driven describe
describe.each([["admin"], ["user"]])("role %s", (role) => { ... });
7. Async hook
beforeEach(async () => { await db.clear(); });
8. Cleanup in afterEach
afterEach(() => { vi.restoreAllMocks(); });
9. Immutability assertion
it("does not mutate input", () => {
const original = [...items];
addItem(items, newItem);
expect(items).toEqual(original);
});
10. Distinct names
it("returns 0 for empty", ...);
it("sums non-empty", ...);
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 │
└─────────────────────────────────────────────────────────┘
Test Name Construction
┌─────────────────────────────────────────────────────────┐
│ describe("cart") │
│ describe("total") │
│ it("sums price times quantity") │
│ │
│ Reporter name: │
│ cart > total > sums price times quantity │
│ │
│ The full name is the concatenation of every level. │
└─────────────────────────────────────────────────────────┘
Table-Driven Expansion
┌─────────────────────────────────────────────────────────┐
│ it.each([ │
│ ["80", 80], │
│ ["443", 443], │
│ ])("parses %s", (input, expected) => { ... }) │
│ │
│ Generates: │
│ ✓ parses 80 │
│ ✓ parses 443 │
│ │
│ One test per row, distinct names │
└─────────────────────────────────────────────────────────┘
Suite Organization
┌─────────────────────────────────────────────────────────┐
│ cart.test.ts │
│ ┌──────────────────────────────────────────┐ │
│ │ describe("cart") │ │
│ │ beforeEach: fresh items │ │
│ │ │ │
│ │ describe("total") │ │
│ │ it: sums │ │
│ │ it: empty │ │
│ │ it.each: table │ │
│ │ │ │
│ │ describe("addItem") │ │
│ │ it: appends │ │
│ │ it: increments │ │
│ │ it: no mutation │ │
│ └──────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
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) |
| Full name | Joined by > in reporter |
| Parameterized | it.each(rows)(name, fn) |
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 .- Name the behavior, not the implementation.
it("increments quantity of an existing item")survives a refactor;it("calls _internalHelper")breaks when the helper is renamed. it.eachreplaces repetition. The table generates one test per row, and the row’s values fill the name placeholders, so failures identify the failing input .
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. The structure should mirror the domain, not the file tree, and the names should describe behavior, not implementation. When a test passes alone but fails in the suite, the cause is shared mutable state; when the hook order is wrong, the cause is a misunderstanding of outermost-first versus innermost-first.
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!