Testing with Vitest
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
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.
A first test
// 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;
}// 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);
});
});npx vitest run # run once (CI)
npx vitest # watch mode: re-runs affected tests on every saveWhen a test fails, Vitest shows the expected and received values and the exact line:
FAIL src/price.test.ts > withTax > adds 20% by default
AssertionError: expected 120 to be 121 // Object.is equality
- Expected
+ Received
- 121
+ 120Matchers you’ll use most
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:
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:
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
tsctoo (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:
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,tscchecks your types — run both.
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.
// ---- 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";// ---- src/cart.test.ts ----
import { describe, expect, expectTypeOf, it, vi } from "vitest";
import { applyCoupon, checkout, CouponError, total, type Coupon } from "./cart.ts";
describe("total", () => {
it("is 0 for an empty cart", () => {
expect(total([])).toBe(0);
});
it("multiplies price by quantity", () => {
expect(total([{ price: 2.5, quantity: 4 }, { price: 1, quantity: 1 }])).toBe(11);
});
});
describe("applyCoupon", () => {
it("applies a percentage and rounds to cents", () => {
expect(applyCoupon(19.99, "SAVE10")).toBe(17.99);
expect(applyCoupon(10, "HALF")).toBe(5);
});
it("rejects unknown coupons", () => {
const code = "FREE" as Coupon; // simulate bad data that got past the types
expect(() => applyCoupon(10, code)).toThrow(CouponError);
expect(() => applyCoupon(10, code)).toThrow("Unknown coupon: FREE");
});
});
describe("checkout", () => {
it("pays the rounded total once", async () => {
const pay = vi.fn((amount: number) => Promise.resolve(`receipt for ${amount}`));
const receipt = await checkout([{ price: 0.1, quantity: 3 }], pay);
expect(pay).toHaveBeenCalledTimes(1);
expect(pay).toHaveBeenCalledWith(0.3);
expect(receipt).toBe("receipt for 0.3");
});
});
describe("types", () => {
it("has precise signatures", () => {
expectTypeOf(total).returns.toEqualTypeOf<number>();
expectTypeOf(applyCoupon).parameter(1).toEqualTypeOf<"SAVE10" | "HALF">();
});
});Summary
- Vitest runs
*.test.tsfiles directly — it strips types, so also runtscto type-check your tests. describe,itandexpectstructure tests; matchers liketoBe,toEqual,toThrowandresolvescheck results.vi.fn()creates typed mock functions you can inspect withtoHaveBeenCalledWith.- Async tests are just
asyncfunctions thatawaitthe code under test. expectTypeOftests types themselves — useful for library code and complex generics.