Unit tests are the cheapest way to keep logic correct as a codebase grows—especially when you ship quickly and refactor often. They turn “hope it works” into “I know it works” for the parts of your system that are easy to break: parsing, formatting, validation, permissions, scheduling rules, and edge cases.
In the AI era, unit testing matters even more. AI can generate code fast, but it can also generate confident mistakes. A small test suite is your safety net: it catches regressions early and makes refactors safe.
Vitest is a modern test runner that feels familiar if you’ve used Jest, but runs fast and plays nicely with TypeScript and ESM.
Why unit testing is important
Unit tests are “small on purpose”: they test one function/module in isolation. That’s powerful because they’re:
- Fast: you can run them on every save (watch mode).
- Reliable: fewer moving parts than E2E tests, so fewer flaky failures.
- Great for refactors: you can improve structure without changing behavior.
- A living spec: tests document what the code must do (including edge cases).
- A guardrail for AI-assisted changes: you can accept helpful code generation while enforcing correctness.
The goal is not 100% coverage. The goal is to protect the logic that would be expensive to debug in production.
Why Vitest
- Fast feedback loop (watch mode is very quick)
- Jest-like API (
describe,it,expect, snapshots) - TypeScript-first with great DX
- Works for Node utilities and UI components (via
jsdom)
Install (TypeScript)
pnpm add -D vitest @vitest/coverage-v8
If you test UI components:
pnpm add -D jsdom @testing-library/react @testing-library/jest-dom
Add scripts
{
"scripts": {
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage"
}
}
Configure Vitest
Create vitest.config.ts:
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node", // or "jsdom" for UI tests
include: ["**/*.{test,spec}.ts", "**/*.{test,spec}.tsx"],
coverage: {
provider: "v8",
reporter: ["text", "html"],
exclude: ["**/*.d.ts", ".next/**", "dist/**", "node_modules/**"],
},
},
});
A simple unit test
src/math.ts:
export function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
src/math.test.ts:
import { describe, expect, it } from "vitest";
import { clamp } from "./math";
describe("clamp", () => {
it("clamps inside bounds", () => {
expect(clamp(5, 0, 10)).toBe(5);
});
it("clamps below min", () => {
expect(clamp(-1, 0, 10)).toBe(0);
});
it("clamps above max", () => {
expect(clamp(11, 0, 10)).toBe(10);
});
});
Mocking (practical patterns)
Vitest uses vi for mocks:
import { vi } from "vitest";
const fn = vi.fn().mockReturnValue("ok");
expect(fn()).toBe("ok");
expect(fn).toHaveBeenCalledTimes(1);
Mock a module:
vi.mock("./time", () => ({ now: () => 123 }));
Fake timers (useful for debounce/interval logic):
vi.useFakeTimers();
// trigger timers...
vi.runAllTimers();
vi.useRealTimers();
Testing React components (optional)
Switch to environment: "jsdom" and add a setup file:
vitest.setup.ts:
import "@testing-library/jest-dom";
Example:
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
function Hello({ name }: { name: string }) {
return <p>Hello {name}</p>;
}
it("renders a greeting", () => {
render(<Hello name="Bara" />);
expect(screen.getByText("Hello Bara")).toBeInTheDocument();
});
What to test (and what not to)
Good unit tests focus on:
- Pure logic (formatters, parsers, validation, mapping)
- Edge cases that break in production
- Behavior, not implementation details
Avoid:
- snapshots for everything (use sparingly)
- brittle tests that mirror internal structure instead of outcomes
The best habit: tests as part of your refactor loop
In the AI era, code can be generated quickly—but mistakes can scale quickly too. Use Vitest to keep changes safe:
- write a failing test (or reproduce the bug)
- implement a small fix
- run tests in watch mode
- refactor with confidence
That feedback loop is the real productivity gain.
