Testing with Vitest

Topic 3 of 4 in Configuration and tooling7 min readIntermediateFree course

Overview

Types prove a lot about your code, but not that it computes the right answers. Tests do that. Vitest is the most popular test runner for modern TypeScript projects: it runs .ts files with no build step, has a Jest-compatible API, and is very fast. This lesson covers everything you need to test real code — including a few things that only make sense in TypeScript.

Setting up

Terminal
npm install -D vitest
npm pkg set scripts.test="vitest run"

No configuration is needed for a Node project. Vitest finds files named *.test.ts (or *.spec.ts) and runs them.

Testing with Vitest. price.test.ts imports describe, expect and it from “vitest” and withTax from “./price.ts”; describe(“withTax”, …) contains it(“adds 20% by default”, () => { expect(withTax(100)).toBe(120); }). Running npx vitest run prints RUN v5.1.2 and then Test Files 1 passed (1), Tests 3 passed (3). Vitest runs .ts files directly, with no separate build step. It strips the types and runs the tests; it does not type-check them. Run tsc –noEmit as well, and use expectTypeOf(value).toEqualTypeOf<T>() when you want to test the types themselves.

A first test

TypeScript
// src/price.ts
export function withTax(amount: number, rate = 0.2): number {
  if (amount < 0) throw new RangeError("amount must not be negative");
  return Math.round(amount * (1 + rate) * 100) / 100;
}
TypeScript
// src/price.test.ts
import { describe, expect, it } from "vitest";
import { withTax } from "./price.ts";

describe("withTax", () => {
  it("adds 20% by default", () => {
    expect(withTax(100)).toBe(120);
  });

  it("accepts a custom rate", () => {
    expect(withTax(50, 0.1)).toBe(55);
  });

  it("rejects negative amounts", () => {
    expect(() => withTax(-1)).toThrow(RangeError);
  });
});
Terminal
npx vitest run      # run once (CI)
npx vitest          # watch mode: re-runs affected tests on every save

When a test fails, Vitest shows the expected and received values and the exact line:

Text
 FAIL  src/price.test.ts > withTax > adds 20% by default
AssertionError: expected 120 to be 121 // Object.is equality

- Expected
+ Received

- 121
+ 120

Matchers you’ll use most

TypeScript
expect(value).toBe(42);                    // same value (===, for primitives)
expect(obj).toEqual({ id: 1, name: "A" }); // deep equality for objects and arrays
expect(obj).toMatchObject({ id: 1 });      // at least these properties
expect(list).toContain("tea");
expect(list).toHaveLength(3);
expect(value).toBeUndefined();
expect(0.1 + 0.2).toBeCloseTo(0.3);        // floats
expect(() => parse("x")).toThrow("Invalid input");
expect(text).toMatch(/^order-\d+$/);

Matchers are typed: expect(withTax(100)).toBe("120") is a type error, because a number can never equal a string.

Testing async code

Make the test async and await the code — or use resolves / rejects:

TypeScript
it("loads a user", async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe("Asha");
});

it("fails for unknown ids", async () => {
  await expect(fetchUser(99)).rejects.toThrow("User 99 not found");
});

Forgetting the await before expect(...).rejects makes the test pass without checking anything — typescript-eslint’s no-floating-promises catches that.

Mocks with vi.fn

When code calls something you don’t want to run for real — a payment API, an email sender, the clock — pass in a mock function:

TypeScript
import { vi } from "vitest";

const pay = vi.fn((amount: number) => Promise.resolve(`receipt for ${amount}`));
await checkout(cart, pay);

expect(pay).toHaveBeenCalledTimes(1);
expect(pay).toHaveBeenCalledWith(53.48);

vi.fn keeps the type of the function you give it, so the mock must match the signature the code expects — a wrongly-shaped mock is a type error. This is one reason to design code so dependencies are passed in (parameters, constructor arguments) rather than imported directly: it makes testing trivial. (Vitest can also replace whole modules with vi.mock, and fake timers with vi.useFakeTimers().)

Tests and types

Vitest strips types without checking them, exactly like Node. A test file can contain type errors and still run. So:

  • run tsc too (npm run check), and include your test files in the tsconfig;
  • use the types to your advantage — fewer tests for “what if someone passes a string?”, because TypeScript already prevents that. Focus tests on behaviour: values, edge cases, errors.

To feed deliberately invalid data into a test (simulating bad input that got past the types), cast it explicitly so the intent is visible: "FREE" as Coupon, or // @ts-expect-error.

Testing types with expectTypeOf

For library code and complex generics, the types themselves are worth testing:

TypeScript
import { expectTypeOf } from "vitest";

expectTypeOf(withTax).returns.toEqualTypeOf<number>();
expectTypeOf(parseOrder).parameter(0).toEqualTypeOf<string>();
expectTypeOf(first([1, 2])).toEqualTypeOf<number | undefined>();

These assertions are checked by tsc (at run time they do nothing), so they fail your check step if a type changes unexpectedly. Vitest can also run them itself with vitest --typecheck.

What to test

  • Pure logic first: calculations, parsing, validation, state transitions. Easy to test, and where most bugs are.
  • Edge cases: empty inputs, zero, the largest value, unicode, duplicates.
  • Error paths: invalid input, failed requests, timeouts.
  • Every bug you fix: write a failing test first, then fix the code — the bug can never silently return.

Keep tests independent (no shared state between them) and named after the behaviour they check.

Remember: *.test.ts + describe/it/expect + npx vitest. Vitest runs your code, tsc checks your types — run both.

Exercise

Test a shopping cart module

Write src/cart.test.ts for the src/cart.ts module in the starter. Cover: (1) an empty cart totals 0; (2) quantities multiply the price; (3) a percentage coupon is applied and rounded to 2 decimals; (4) an unknown coupon throws a CouponError (use toThrow(CouponError) and check the message); (5) checkout awaits the payment function exactly once with the rounded total (use vi.fn returning a resolved promise); (6) a type test with expectTypeOf that total returns number and that applyCoupon’s second parameter only accepts the coupon codes. Run npx vitest run and also npx tsc — both should pass.

TypeScript
// ---- src/cart.ts ----
export type Line = { price: number; quantity: number };
export type Coupon = "SAVE10" | "HALF";

export class CouponError extends Error {
  override name = "CouponError";
}

const RATES: Record<Coupon, number> = { SAVE10: 0.1, HALF: 0.5 };

export function total(lines: readonly Line[]): number {
  return lines.reduce((sum, line) => sum + line.price * line.quantity, 0);
}

export function applyCoupon(amount: number, code: Coupon): number {
  const rate = RATES[code];
  if (rate === undefined) throw new CouponError(`Unknown coupon: ${code}`);
  return Math.round(amount * (1 - rate) * 100) / 100;
}

export async function checkout(lines: readonly Line[], pay: (amount: number) => Promise<string>): Promise<string> {
  const amount = Math.round(total(lines) * 100) / 100;
  return pay(amount);
}

// ---- src/cart.test.ts ----
import { describe, expect, expectTypeOf, it, vi } from "vitest";

Summary

  • Vitest runs *.test.ts files directly — it strips types, so also run tsc to type-check your tests.
  • describe, it and expect structure tests; matchers like toBe, toEqual, toThrow and resolves check results.
  • vi.fn() creates typed mock functions you can inspect with toHaveBeenCalledWith.
  • Async tests are just async functions that await the code under test.
  • expectTypeOf tests types themselves — useful for library code and complex generics.