Skip to content
jshacks.dev
Testing

Arrange, Act, Assert

Arrange, Act, Assert splits a test into setup, one action and checks. See it in Vitest with builders, async tests, common mistakes and variants.

7 min read
Summarize in AI
Flat illustration of a test run shown as a row of passing dots, with the Vitest, Mocha, Cypress and Jest logos.

Arrange, Act, Assert, usually written AAA, is the most common way to structure a unit test. It splits a test into three parts in a fixed order: set up what the test needs, perform the one action under test and check the result. The pattern sounds almost too simple to matter, and its value is that it makes tests readable at a glance, keeps each one focused and gives you a way to notice when a test has grown too big. This post explains each phase with JavaScript examples in Vitest 4 on Node.js 24, shows how to handle async code and errors, covers the common mistakes, such as several acts in one test or logic in the assertions, and looks at related styles, like Given-When-Then. The pattern was described by Bill Wake and is widely used in test guidance such as the Vitest guide.

The three phases

Arrange builds the world: create objects, prepare input data, configure fakes. Act does the thing being tested, ideally with one call. Assert checks that the outcome is what you expected. Separating the phases with a blank line, or with comments while you learn the pattern, makes the structure visible.

cart.jsJavaScript
export class Cart {
  #items = [];

  add(name, price, quantity = 1) {
    this.#items.push({ name, price, quantity });
  }

  get total() {
    return this.#items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  }

  get count() {
    return this.#items.reduce((sum, item) => sum + item.quantity, 0);
  }
}
cart.test.jsJavaScript
import { expect, test } from "vitest";
import { Cart } from "./cart.js";

test("totals the price of every item by quantity", () => {
  // Arrange
  const cart = new Cart();
  cart.add("book", 12, 2);
  cart.add("pen", 3);

  // Act
  const total = cart.total;

  // Assert
  expect(total).toBe(27);
});
Text
 ✓ cart.test.js (1 test)
   Test Files  1 passed (1)
        Tests  1 passed (1)

The arrangement builds a cart with two lines. The act reads the total, which is the behavior under test. The assertion checks the number: 12 times 2 plus 3 is 27. A reader can see what the test needs, what it does and what it expects without reading the implementation of Cart.

The comments are a teaching aid. In real code, many teams drop them and rely on blank lines, since the shape is recognizable. When a test is short, such as a one-line arrangement, the blank lines may not be needed either.

Why the order matters

Keeping the phases in order and separate gives a few benefits. A failing test is easier to read, because you know where to look: if the failure is in the arrange part, the setup is broken, and if it is in the assert, the behavior is wrong. Tests stay focused, since a single act implies a single behavior. And the structure resists a common mistake, which is testing while setting up: interleaving actions and assertions until the test is a script.

Consider a test that violates the pattern.

mixed.test.jsJavaScript
import { expect, test } from "vitest";
import { Cart } from "./cart.js";

test("cart works", () => {
  const cart = new Cart();
  expect(cart.total).toBe(0);
  cart.add("book", 12);
  expect(cart.total).toBe(12);
  cart.add("pen", 3);
  expect(cart.total).toBe(15);
  expect(cart.count).toBe(2);
});
Text
 ✓ mixed.test.js (1 test)

It passes, and it is poor. The name says nothing, there are three acts, and a failure at the second assertion does not say which behavior is broken. Splitting it gives three tests that each read as a rule: an empty cart totals zero, adding an item adds its price, and adding two items counts both. Each has one act.

Arrange without repetition

Arrangement is often the longest part, and repeating it in every test hides the point of each one. Share it with a helper, a builder or a beforeEach hook, and keep the details that matter to a particular test visible in that test.

builder.test.jsJavaScript
import { describe, expect, test } from "vitest";
import { Cart } from "./cart.js";

function cartWith(...lines) {
  const cart = new Cart();
  for (const [name, price, quantity] of lines) cart.add(name, price, quantity);
  return cart;
}

describe("Cart", () => {
  test("an empty cart has a total of zero", () => {
    const cart = cartWith();

    expect(cart.total).toBe(0);
  });

  test("multiplies each price by its quantity", () => {
    const cart = cartWith(["book", 12, 2]);

    expect(cart.total).toBe(24);
  });

  test("counts the quantity of every line", () => {
    const cart = cartWith(["book", 12, 2], ["pen", 3, 5]);

    expect(cart.count).toBe(7);
  });
});
Text
 ✓ builder.test.js (3 tests)
   Test Files  1 passed (1)
        Tests  3 passed (3)

The helper cartWith removes boilerplate, and each test shows its own data. In these tests the act and the assert are the same expression, cart.total inside expect, which is acceptable when the act is a simple read. When the act is a call with side effects, give it its own line so the phases stay visible.

A hook such as beforeEach is useful for setup shared by every test in a group, such as a fresh object. Use it for infrastructure, and keep test-specific data in the test, because moving it into a hook makes the reader scroll up to understand a test.

The act is one thing

The act should be a single call or action, ideally one line. If you need several steps to get to the behavior, the extra steps probably belong in the arrange phase. If the action itself has several steps, the test may be at the wrong level, or the unit may be doing too much.

transfer.test.jsJavaScript
import { expect, test } from "vitest";
import { Account } from "./account.js";

test("transfer moves money from one account to another", () => {
  const from = new Account(100);
  const to = new Account(20);

  from.transferTo(to, 30);

  expect(from.balance).toBe(70);
  expect(to.balance).toBe(50);
});
Text
 ✓ transfer.test.js (1 test)

There is one act, transferTo, and two assertions that describe the one outcome. Multiple assertions are fine when they all describe the result of that one act. The rule is one act, not one assertion.

Async code

The pattern holds for promises and callbacks. Await the act, then assert. Make sure the test function is async and that nothing is left un-awaited, or the test ends before the assertion runs.

async.test.jsJavaScript
import { expect, test } from "vitest";
import { findUser } from "./users.js";

test("finds a user by email", async () => {
  const users = [{ id: 1, email: "[email protected]" }];
  const repository = { find: async (email) => users.find((u) => u.email === email) ?? null };

  const user = await findUser(repository, "[email protected]");

  expect(user).toEqual({ id: 1, email: "[email protected]" });
});
Text
 ✓ async.test.js (1 test)

For code that is expected to reject, the act is the call that returns the rejected promise, and the assertion uses rejects.

rejects.test.jsJavaScript
import { expect, test } from "vitest";
import { findUser } from "./users.js";

test("rejects when the email is empty", async () => {
  const repository = { find: async () => null };

  const result = findUser(repository, "");

  await expect(result).rejects.toThrow("Email is required");
});
Text
 ✓ rejects.test.js (1 test)

Here the act produces the promise without awaiting it, and the assert awaits it through expect. That keeps the phases separate even though the failure is asynchronous.

Testing errors

When the behavior is a thrown error, the act is wrapped in a function so that the matcher can catch it. This is the one place where the act and assert share a line.

throws.test.jsJavaScript
import { expect, test } from "vitest";
import { parseAge } from "./parse-age.js";

test("throws for a negative age", () => {
  const input = "-5";

  const act = () => parseAge(input);

  expect(act).toThrow("Age must be zero or more");
});
Text
 ✓ throws.test.js (1 test)

Naming the function act keeps the pattern visible. Do not call parseAge("-5") directly in the test, because the thrown error would fail the test before the assertion runs.

Common mistakes

Several acts. A test that performs two actions checks two behaviors, and one failing hides the other. Split it.

Logic in the test. Loops, conditions and computed expected values make the test a program that needs its own tests. Write the expected value as a literal. If you compute it with the same formula as the code, the test passes even when the formula is wrong.

literal.test.jsJavaScript
import { expect, test } from "vitest";
import { applyTax } from "./tax.js";

test("adds 20 percent tax", () => {
  const result = applyTax(50, 0.2);

  expect(result).toBe(60);
});
Text
 ✓ literal.test.js (1 test)

The expected value, 60, is written by hand. A test that said expect(result).toBe(50 + 50 * 0.2) would repeat the production formula and could share its bug.

An arrange that does too much. If setting up the world takes forty lines, the unit probably has too many dependencies. The long arrangement is a signal about the design, not only the test.

An assertion on the arrangement. Asserting that the setup worked belongs in a separate test, or nowhere.

Asserting too little or too much. An assertion that only checks that a value is defined says almost nothing, while an assertion on the whole object with every incidental field makes the test brittle. Assert what the behavior promises.

Given, When, Then is the same idea in the language of behavior: given a context, when an event happens, then an outcome follows. It maps directly onto arrange, act and assert, and it is used in behavior-driven development and tools that read feature files. Some teams write tests with describe blocks named after the context and test names starting with "when" or "it". Another variant is Setup, Exercise, Verify, Teardown from the xUnit literature, which adds a cleanup phase for resources, handled in Vitest by afterEach. The names differ, the discipline is the same: set up, do one thing, check.

Share

Keep reading

Flat illustration of a test report with one failing test, with the Vitest, GitHub Actions and Jest logos.
Testing

The Testing Pyramid and the Testing Trophy

Compare the testing pyramid and the testing trophy for JavaScript apps: what each says about unit, integration and end-to-end tests, and how to choose.

8 min read
Flat illustration of a test report with one failing test, with the Vitest, Cypress, Jest and GitHub Actions logos.
Testing

Unit vs Integration vs End-to-End Tests

Compare unit, integration and end-to-end tests with one JavaScript feature tested at each level: scope, speed, dependencies and what each catches.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.