Skip to content

Unit Testing

How to write fast, isolated unit tests that pinpoint failures in individual functions.

What you'll learn

  • What makes a good unit test: fast, isolated, repeatable, self-verifying
  • The Arrange-Act-Assert (AAA) structure
  • How to isolate a unit by replacing its dependencies
  • Naming conventions that make failures self-explanatory

Concept

What Is a Unit?

A unit is the smallest piece of code that has a single, well-defined responsibility — typically one pure function or one method of a class. The defining trait of a unit test is isolation: the unit under test must not reach out to the network, the filesystem, the database, or the clock. Any such dependency is replaced with a test double so the test exercises only the unit's own logic.

Properties of a Good Unit Test

A good unit test follows the FIRST principles: Fast (runs in milliseconds), Isolated (independent of other tests and of order), Repeatable (gives the same result every time), Self-verifying (passes or fails automatically without manual inspection), and Timely (written close to the code it tests). A suite of thousands of FIRST unit tests can run in a few seconds and give you a precise map of what is broken.

Arrange-Act-Assert

The AAA pattern keeps tests readable. Arrange sets up the inputs and any fakes. Act calls the unit under test exactly once. Assert checks the result (and, if needed, that the fakes were called correctly). Keeping these three phases visually separated — often with a blank line — makes the test's intent obvious and failures easy to diagnose.

Naming

A test name should describe the scenario and the expected outcome, not the implementation. Names like adds_discount_for_premium_customer or throws_when_quantity_is_negative turn a failing test list into a readable spec. Avoid generic names like test1 or works — they tell you nothing when they break.

In Practice

When you sit down to write a unit test, start by identifying the smallest piece of behavior worth verifying. Arrange the inputs as plainly as possible, call the function once, and assert on the return value. If the function has a dependency that reaches outside — a database, the network, the clock — replace that dependency with a stub so the test stays fast and deterministic. Keep each test focused on one assertion concept; if you find yourself checking the return value and a side effect in the same test, split it into two named cases. Run the suite constantly while coding — the sub-second feedback is where the productivity gain comes from. Over time, a folder of well-named unit tests becomes a precise, readable specification of what your module does and how it should behave at its edges.

Example

              // Code under test
export function calculateTotal(items: { price: number; qty: number }[]): number {
  return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}

// Unit test (Vitest)
import { describe, it, expect } from "vitest";
import { calculateTotal } from "./cart";

describe("calculateTotal", () => {
  it("sums price * qty for every item", () => {
    const items = [
      { price: 10, qty: 2 },
      { price: 5, qty: 4 },
    ];
    expect(calculateTotal(items)).toBe(40);
  });

  it("returns 0 for an empty cart", () => {
    expect(calculateTotal([])).toBe(0);
  });
});
            

calculateTotal is a pure function with no side effects, making it ideal for unit testing. Each test follows Arrange-Act-Assert and the names describe the expected behavior.

Try it

  • Code Diff

    Compare expected and actual values when a unit test fails.

  • JSON Formatter

    Pretty-print the data structures your assertions compare.

Common mistakes

The mistake

Testing multiple things in one test

The fix

One test, one assertion concept. If a test checks both the return value and a side effect, split it into two named tests.

The mistake

Depending on the current date or random values

The fix

Inject a clock or a random source so the test controls the value. Non-determinism makes tests flaky and erodes trust.

Practice Unit Testing

3 exercises

Practice Unit Testing

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors