Skip to content
FrontDepth, Home

Testing

Unit tests and test doubles

Writing unit tests with Vitest: test and describe, equality matchers, errors and promises, making code testable with pure functions and injected dependencies, the five kinds of test doubles, vi.fn and vi.spyOn and how to restore them, test isolation, over-mocking and the limits of snapshot tests.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

A first unit test with Vitest

A calls one piece of code with chosen inputs and checks the output. The easiest code to test is a pure function: its result depends only on its arguments, and it changes nothing outside itself. There is nothing to set up, clean up or wait for: you call it and compare.

TypeScript
// price.ts
export function formatPrice(cents: number, currency = "AZN"): string {
  if (!Number.isInteger(cents)) throw new TypeError("cents must be an integer");
  return `${(cents / 100).toFixed(2)} ${currency}`;
}
TypeScript
// price.test.ts
import { describe, expect, it, test } from "vitest";
import { formatPrice } from "./price";

describe("formatPrice", () => {
  it("formats cents with two decimals", () => {
    expect(formatPrice(1999)).toBe("19.99 AZN");
  });

  it("uses the currency it is given", () => {
    expect(formatPrice(250, "EUR")).toBe("2.50 EUR");
  });

  test.each([
    [0, "0.00 AZN"],
    [5, "0.05 AZN"],
    [100000, "1000.00 AZN"],
  ])("formats %i as %s", (cents, expected) => {
    expect(formatPrice(cents)).toBe(expected);
  });
});
  • test(name, fn) defines a test. it is the same function under another name, so that it("formats…") reads as a sentence.
  • describe(name, fn) groups tests; a failure is reported as formatPrice > formats cents with two decimals.
  • expect(value) starts an assertion and a matcher such as toBe finishes it. A failing matcher throws, and the test fails. .not negates any matcher: expect(x).not.toBe(0).
  • test.each runs the same test once for each row of a table; %i and %s in the name are replaced by the row's values.

Vitest doesn't make these functions global by default (globals: false), so you import them from "vitest". Tests run in a Node.js environment by default, which suits pure logic; component tests switch the environment option to jsdom or happy-dom. Run npx vitest to watch files while you work and npx vitest run for a single run.

Choosing the cases

Each test is one example of the function's contract: a typical input, the boundaries (zero, the largest realistic value) and invalid input. Name each test after the rule it shows. Write expected values as literals ("19.99 AZN"), never recomputed with the same formula the code uses: a test that repeats the calculation repeats its bugs.

If a function is hard to test this way because it reads the clock, calls the network or needs a rendered component, that is usually a hint to split it: a pure core that holds the rules, and a thin layer that does the side effects.

JuniorConcept

toBe, toEqual and toStrictEqual

toBe compares with Object.is: the same as ===, except that NaN equals NaN and 0 differs from -0. For strings, numbers and booleans that is what you want. For objects and arrays it checks identity, so two objects with the same contents are not toBe-equal:

TypeScript
const a = { id: 1, tags: ["new"] };
const b = { id: 1, tags: ["new"] };

expect(a).toBe(a);
expect(a).not.toBe(b);
expect(a).toEqual(b);

toEqual compares recursively: the same keys with equal values, all the way down. The Vitest docs list three ways in which it is more lenient than toStrictEqual:

  • keys whose value is undefined are ignored: { a: undefined, b: 2 } equals { b: 2 };
  • array holes are not checked: [, 1] equals [undefined, 1];
  • the object's type is not checked: a class instance equals a plain object with the same fields.
TypeScript
class Money {
  amount: number;
  currency: string;
  constructor(amount: number, currency: string) {
    this.amount = amount;
    this.currency = currency;
  }
}

const price = new Money(5, "AZN");
expect(price).toEqual({ amount: 5, currency: "AZN" });
expect(price).not.toStrictEqual({ amount: 5, currency: "AZN" });
expect({ amount: 5, note: undefined }).toEqual({ amount: 5 });
expect({ amount: 5, note: undefined }).not.toStrictEqual({ amount: 5 });

Use toStrictEqual when the exact shape is part of the contract: a reducer's next state, a payload sent to an API, a value that must be an instance of a class. Use toEqual when "the same data" is enough.

Other everyday matchers

  • toMatchObject(subset): the object has at least these properties, checked recursively; extra properties are allowed. Good for "the new order has status pending" without listing every field.
  • toContain(item): an item in an array, or a substring in a string. toHaveLength(n) checks .length.
  • toBeCloseTo(n, digits?): for floating-point results. 0.1 + 0.2 is 0.30000000000000004, so toBe(0.3) fails, while toBeCloseTo(0.3) passes; it checks 2 digits after the point unless you pass another number.
  • toBeNull(), toBeUndefined(), toBeTruthy(), toBeFalsy(). Prefer the most specific matcher: if the value must be the boolean true, write toBe(true), because toBeTruthy() also accepts 1 and "no".
JuniorConcept

Testing errors and promises

Errors

toThrow calls a function and checks that it throws. Pass it the function, not the result of calling it:

TypeScript
expect(() => formatPrice(1.5)).toThrow("cents must be an integer");
expect(() => formatPrice(1.5)).toThrow(/integer/);

// ✗ formatPrice throws while the argument is evaluated, before expect runs
expect(formatPrice(1.5)).toThrow();

In the last line JavaScript calls formatPrice(1.5) to compute the argument for expect, so the error escapes before toThrow can catch it, and the test fails with that error. The Vitest docs put it plainly: you must wrap the code in a function, otherwise the error will not be caught. A string argument matches a substring of the message and a regular expression a pattern. Check the message, not only that "something" was thrown: a typo that throws TypeError: x is not a function also satisfies a bare toThrow().

Promises

A test function can be async; Vitest waits for the promise it returns. Either await the value and use ordinary matchers, or use .resolves and .rejects:

TypeScript
const api = {
  getUser: async (id: number) => (id === 1 ? { id, name: "Leyla" } : null),
};

test("loads a user", async () => {
  const user = await loadUser(1, api);
  expect(user.name).toBe("Leyla");
});

test("rejects an unknown id", async () => {
  await expect(loadUser(999, api)).rejects.toThrow("User 999 not found");
});

.resolves and .rejects turn the matcher into a promise, so the line must be awaited. Since Vitest 5.0 such an assertion fails the test if it is not awaited; before that, Vitest awaited it at the end of the test and only printed a warning. The general rule is older than any test runner: a promise that nobody awaits or returns is not part of the test, so its failure is not the test's failure.

For code that reports results through a callback, expect.assertions(n) at the top of the test checks that exactly n assertions ran, and expect.hasAssertions() that at least one did. Both catch the test whose only expect sits in a callback that never fired.

The small api object is a hand-written stand-in for the real client: the simplest kind of test double, and the reason loadUser takes the client as a parameter instead of importing it.

MiddleExample

Making code testable: pure functions and injected dependencies

Logic written inside a component can only be tested by rendering the component. The same logic as a pure function can be tested with one line per case. A typical refactor:

TSX
// before: the rules live in the component
function CheckoutSummary({ items, coupon }: Props) {
  let subtotal = 0;
  for (const item of items) subtotal += item.price * item.quantity;
  const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
  const shipping = subtotal - discount >= 100 ? 0 : 5;
  return <Summary subtotal={subtotal} discount={discount} shipping={shipping} />;
}
TypeScript
// after: a pure function holds the rules
export function summarize(items: Item[], coupon?: string) {
  const subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
  const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
  const shipping = subtotal - discount >= 100 ? 0 : 5;
  return { subtotal, discount, shipping, total: subtotal - discount + shipping };
}

The component now calls summarize(items, coupon) and renders the result. Each rule, and the way the rules interact (does the discount count towards free shipping?), gets a fast unit test, and one or two component tests check that the numbers reach the screen.

Side effects at the edge, dependencies passed in

Not everything can be pure: code reads the clock, calls the network, writes to storage. Keep those calls at the edge, and pass them in instead of reaching for them from inside:

TypeScript
type Deps = {
  now: () => Date;
  post: (order: Order) => Promise<void>;
};

export async function placeOrder(cart: Cart, { now, post }: Deps) {
  if (cart.items.length === 0) throw new Error("Cart is empty");
  await post({ items: cart.items, placedAt: now().toISOString() });
}

The app calls placeOrder(cart, { now: () => new Date(), post: api.postOrder }). A test passes a fixed clock and a function that records what it receives:

TypeScript
test("stamps the order with the current time", async () => {
  const post = vi.fn(async (_order: Order) => {});
  const now = () => new Date("2026-11-16T10:00:00Z");

  await placeOrder({ items: [tea] }, { now, post });

  expect(post).toHaveBeenCalledWith({
    items: [tea],
    placedAt: "2026-11-16T10:00:00.000Z",
  });
});

This is dependency injection: the caller provides the collaborators. It needs no special tooling and shows the dependencies in the function's signature. In React the same idea appears as props (onSubmit) or context.

The result is a large pure core that is cheap to test thoroughly, and a thin shell of components and adapters that needs only a few tests.

MiddleConcept

Test doubles: dummy, stub, spy, mock and fake

A is any object or function that stands in for a real collaborator during a test, the way a stunt double stands in for an actor. Gerard Meszaros introduced the term and five kinds of doubles in xUnit Test Patterns (2007); Martin Fowler's short definitions in TestDouble and Mocks Aren't Stubs are the ones usually quoted:

  • Dummy: passed around but never used; it only fills a parameter list. A logger argument on a code path that never logs.
  • Stub: gives canned answers to the calls made during the test. getRates: () => ({ USD: 1.7 }) makes a currency conversion predictable.
  • Spy: a stub that also records how it was called, so the test can check afterwards which message was "sent" and how many times.
  • Mock: pre-programmed with expectations of the calls it should receive. It can fail on a call it doesn't expect, and at the end it is verified that every expected call happened.
  • Fake: a working implementation with a shortcut that makes it unfit for production, such as an in-memory repository instead of a database.
TypeScript
// a fake: real behaviour, kept in memory
class InMemoryOrders implements OrderRepository {
  #orders = new Map<string, Order>();
  async save(order: Order) {
    this.#orders.set(order.id, order);
  }
  async findById(id: string) {
    return this.#orders.get(id) ?? null;
  }
}

"Mock" in everyday speech

vi.fn() creates a function that records every call and returns whatever you program, so in Meszaros' terms it is a spy that can also act as a stub. Vitest, like Jest, calls it a mock function, and most developers say for any double. That is fine in conversation. The distinction matters when you decide what to assert:

  • With a stub or a fake, you check the result of the code under test: the returned total, what the fake repository holds afterwards. Fowler calls this state verification.
  • With a spy or a mock, you check the calls themselves. Fowler calls this behaviour verification, notes that "only mocks insist upon behavior verification", and that tests written this way are "more coupled to the implementation".

Picking one

Use the real collaborator when it is fast and deterministic, such as your own pure helpers. Use a fake when the real one is slow or external but you need realistic behaviour across calls (save, then find). Use a stub to force a specific answer: an error, an empty list, a rate. Check calls with a spy only when the call itself is the outcome the caller cares about, such as an email being sent or onSubmit receiving the form values; otherwise assert on the result.

MiddleFramework

vi.fn, vi.spyOn and restoring them

vi.fn(impl?) creates a new mock function. Without an implementation it returns undefined; with one, it runs it and records the call:

TypeScript
import { expect, test, vi } from "vitest";

test("reports each failed upload", () => {
  const report = vi.fn();
  reportFailures([{ name: "a.png", ok: false }, { name: "b.png", ok: true }], report);

  expect(report).toHaveBeenCalledTimes(1);
  expect(report).toHaveBeenCalledWith("a.png failed");
});

Program it with mockReturnValue(v), mockReturnValueOnce(v) (next call only), mockResolvedValue(v), mockRejectedValue(e) or mockImplementation(fn). Check it with toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith and toHaveBeenLastCalledWith, or read report.mock.calls (one array of arguments per call) and report.mock.results. For typed code, vi.fn<typeof sendEmail>() makes TypeScript check the programmed values against the real signature. One trap: Vitest stores arguments by reference, so if the code mutates an object after passing it, toHaveBeenCalledWith compares against the mutated object.

vi.spyOn(object, "method") replaces a method on an existing object with a mock that still calls the original by default. Use it to watch a real method, or chain .mockImplementation() or .mockReturnValue() to replace its behaviour:

TypeScript
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
parseConfig({ retries: "3" });
expect(warn).toHaveBeenCalledWith("retries should be a number");
warn.mockRestore();

Clear, reset, restore

A spy on a shared object such as console stays in place after the test unless something puts the original back. Each method does more than the previous one:

clears call historyresets the implementationputs the original method back
mockClear()yesnono
mockReset()yesyesno
mockRestore()yesyesyes, for vi.spyOn

"Resets" means back to what the mock was created with: vi.fn(impl) returns to impl, vi.fn() to returning undefined, and a vi.spyOn spy to calling the real method. On a vi.fn() mock, mockRestore() does the same as mockReset().

vi.clearAllMocks() and vi.resetAllMocks() apply the first two to every mock. vi.restoreAllMocks() only puts back methods replaced by vi.spyOn; it does not clear history or reset implementations. The config options clearMocks, mockReset and restoreMocks call them automatically before each test. Since Vitest 5, clearMocks is on by default, while mockReset and restoreMocks stay off, so enable restoreMocks: true (or restore in afterEach) when tests spy on shared objects.

MiddleConcept

Setup, teardown and test isolation

Every test should give the same result whether it runs alone, first or last. Tests that share mutable state pass or fail depending on their order:

TypeScript
// ✗ one cart for the whole file
const cart = createCart();

test("adds an item", () => {
  cart.add(tea);
  expect(cart.count()).toBe(1);
});

test("starts empty", () => {
  expect(cart.count()).toBe(0);
});

The second test fails after the first, and passes when run alone. Create fresh state for every test, inside the test or in a hook:

TypeScript
let cart: Cart;

beforeEach(() => {
  cart = createCart();
});

Vitest's hooks apply to the current file, or to the current describe block when declared inside one: beforeEach and afterEach run around every test, beforeAll and afterAll once around all of them. afterEach runs even when the test failed, so clean-up belongs there. beforeEach may also return a clean-up function, which Vitest runs after the test, after the afterEach hooks; that keeps setup and teardown side by side. onTestFinished(fn) registers clean-up from inside the test itself.

TypeScript
beforeEach(() => {
  const spy = vi.spyOn(console, "error").mockImplementation(() => {});
  return () => spy.mockRestore();
});

What Vitest isolates, and what it doesn't

  • Test files run in separate environments by default (isolate: true), so module state from one file doesn't leak into another.
  • Tests in the same file share module-level variables, globalThis, the simulated DOM and any spy that wasn't restored. Vitest runs them in the order they are written, which hides order dependence: a test that only passes after another one keeps passing until someone runs it alone or shuffles the order with --sequence.shuffle.
  • Mock call history is cleared before each test since Vitest 5 (clearMocks: true), so toHaveBeenCalledTimes(1) counts only the current test's calls. Implementations set with mockReturnValue are kept unless mockReset is on, and spied methods stay replaced unless restoreMocks is on.

Keep beforeAll for expensive setup that tests only read; anything a test changes should be created for that test. The same applies outside memory: tests that write to the same temporary file, database rows or port depend on each other and can collide when Vitest runs files in parallel.

SeniorPitfalls

Over-mocking

A double removes a dependency's behaviour from the test. Kent C. Dodds warns in Write tests. Not too many. Mostly integration.: "When you mock something you're removing all confidence in the integration between what you're testing and what's being mocked." Used everywhere, doubles produce tests that stay green while the product is broken.

TypeScript
vi.mock("./cart-store");
vi.mock("./pricing");
vi.mock("./orders-api");

test("checkout", async () => {
  vi.mocked(loadCart).mockResolvedValue(cart);
  vi.mocked(calculateTotal).mockReturnValue(42);

  await checkout("c1");

  expect(loadCart).toHaveBeenCalledWith("c1");
  expect(calculateTotal).toHaveBeenCalledWith(cart);
  expect(submitOrder).toHaveBeenCalledWith({ cartId: "c1", total: 42 });
});

This test restates the implementation line by line. It breaks when the code is reorganised (pricing split into two functions) and passes when calculateTotal returns a wrong number, because 42 is whatever the test said.

Signs of over-mocking:

  • most assertions are toHaveBeenCalledWith on the project's own modules;
  • stubbed return values are invented rather than taken from what the real collaborator returns, and drift from it over time.

What to replace

Fowler describes two styles. The classical one uses "real objects if possible and a double if it's awkward to use the real thing"; the mockist one "will always use a mock for any object with interesting behavior". Dodds, in the same article, calls "stop mocking so much stuff" the biggest thing you can do to write more integration tests. In practice that means keeping your own modules real (pricing, formatting, reducers, the store) and replacing what is slow, non-deterministic or outside your process: the network, the clock, randomness, third-party SDKs. When you do replace, replace at the boundary: a fake HTTP layer is used by all of your code the same way the real one is, while a stub of your own fetch wrapper skips the wrapper's logic.

Injection or vi.mock?

vi.mock(path, factory?) swaps a module for every importer in the test file. Vitest hoists the call above the imports, and since Vitest 5 it throws if the call is not at the top level of the file. It works without changing the code under test, which is why it is easy to overuse: the dependency is invisible in the code and the replacement applies to the whole file.

Injected dependencies (parameters, props, context) are explicit and chosen per test. A practical split: inject what you own and what varies between tests; use vi.mock for what can't easily be passed in, such as a third-party module imported deep in the tree or a module with side effects on import.

SeniorConcept

Snapshot tests and their limits

expect(value).toMatchSnapshot() serialises the value and compares it with the copy saved the first time the test ran, in a __snapshots__/<file>.snap file next to the test. toMatchInlineSnapshot() writes that copy into the test file itself, which keeps small snapshots visible where they are checked.

TypeScript
test("formats a receipt", () => {
  expect(formatReceipt(order)).toMatchSnapshot();
});

On later runs any difference fails the test with a diff. If the change is intended, update the stored copy with vitest -u or the u key in watch mode. In CI Vitest never writes snapshots, so a missing, changed or obsolete one fails the run. Snapshot files are code: they are committed and reviewed with the change.

Where snapshots help

  • large, structured output that must not change by accident: a serializer, generated configuration, a formatted error message, a CLI's output;
  • a safety net before refactoring code without tests: record the current output, refactor, confirm nothing changed.

Their limits

  • A snapshot records what the code does, not what it should do. The first run accepts whatever comes out, bugs included. Someone has to read the stored value and confirm it is right.
  • Large snapshots get rubber-stamped. When a 300-line snapshot of a page changes with every markup tweak, reviewers stop reading the diff. The Vitest guide warns that it is easy to accept a broken output "by blindly pressing u".
  • They test implementation details by default. Wrapper elements, class names and attribute order change without any change in behaviour, so whole-component snapshots break on harmless refactors and teach people to update without looking.
  • Dynamic values (dates, generated ids) differ on every run. Property matchers such as toMatchSnapshot({ id: expect.any(Number) }) pin the shape and ignore the value.

The Vitest guide's rule: "use snapshots when you want to protect against any change in the output, and use targeted assertions when you only care about specific properties." For a component, an assertion on the text or the role the user sees states what matters; a snapshot of the whole markup states everything, so it says nothing about what matters.

A useful review question for any snapshot in a pull request: if this diff had been a bug, would the reviewer have noticed? If not, replace the snapshot with a few targeted assertions.

SeniorInterview tips

Interview tips

A 30-second answer. "A unit test calls code with chosen inputs and checks the outputs. Pure functions are the easiest to test, so I keep business rules out of components. For dependencies I use test doubles, which Gerard Meszaros divides into dummies, stubs, spies, mocks and fakes; in Vitest that is mostly vi.fn and vi.spyOn. I prefer real collaborators and fakes, replace only what is slow or non-deterministic, inject dependencies where I can instead of mocking modules, restore spies after each test, and assert on results rather than calls unless the call is the behaviour."

Questions you are likely to get

  • toBe, toEqual or toStrictEqual? Identity by Object.is; recursive equality that ignores undefined keys and class types; recursive equality that checks them.
  • What is the difference between a stub and a mock? A stub returns canned answers and you check the result (state verification); a mock carries expectations about the calls it receives (behaviour verification). Martin Fowler's Mocks Aren't Stubs is the reference.
  • vi.fn or vi.spyOn? A new function versus a wrapper around an existing method that still calls the original until you replace it.
  • mockClear, mockReset, mockRestore? History; history and implementation; all of that plus the original method back for spies.
  • How do you test code that uses Date.now() or Math.random()? Inject a clock or a random source, or use Vitest's fake timers and vi.setSystemTime for time.

Mistakes that cost points

  • Calling every double a mock and asserting on calls everywhere.
  • expect(fn()).toThrow() instead of expect(() => fn()).toThrow().
  • .rejects or .resolves without await.
  • Spying on a shared object without restoring it.
  • Mocking the module under test, or the project's own pure modules.

Senior signal

Talk about design for testability rather than tools: a pure core with a thin shell, dependencies passed in, and doubles only at boundaries you don't control. Show that you read a test with six mocks as a design smell, and that you know what changed recently, for example that Vitest 5 clears mock history before each test by default and fails unawaited asynchronous assertions.

JuniorReview checklist

What to check when reviewing unit tests and mocks

Use this list when you review unit tests you did not write yourself, in a teammate's pull request or in generated code. Mistakes in tests and doubles don't show up as failures; they show up later as bugs that were "tested" and as tests that break on every refactor.

  • Is the code under test real, with only its collaborators replaced? Find the import of the tested function and make sure no vi.mock or vi.spyOn replaces it; a test that stubs the very function whose result it asserts only tests the stub.
  • Do the assertions check results, or only that doubles were called? toHaveBeenCalledWith fits when the call is the outcome (an event sent, onSubmit called with the values); when every assertion is a call check on the project's own modules, the test restates the implementation and misses wrong values.
  • Is the right equality used? toBe on objects checks identity and fails on equal copies; toEqual ignores undefined keys and class types, so use toStrictEqual where the exact shape matters and toBeCloseTo for floating-point numbers.
  • Are errors and promises asserted correctly? toThrow needs a function, expect(() => fn()).toThrow("message"), and should check the message; .resolves and .rejects must be awaited, and Vitest 5 fails the test when they are not.
  • Is every spy restored and every test independent? A vi.spyOn on console or another shared object needs mockRestore(), restoreMocks: true or clean-up in afterEach, and state shared between tests needs a beforeEach. Run the file with --sequence.shuffle to expose order dependence.
  • Do stubbed values match what the real collaborator returns? An invented shape ({ price } where the real API returns { unitPrice }) lets tests pass against a contract that doesn't exist; type the double with vi.fn<typeof realFn>() or vi.mocked() so TypeScript catches the drift.
  • Is each snapshot small, correct and explained? A snapshot accepts whatever the code produced on its first run, so read the stored value, and ask why every updated snapshot in the diff changed.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions