Lesson 19 of 50JavaScript in depth
Testing JavaScript and TypeScript with Vitest
Write fast, trustworthy unit tests with Vitest: matchers, test tables, async code, mocks that do not lie, fake timers, coverage and snapshots.
A teammate changes how discount codes are rounded. The code review looks fine, the app builds, and two days later finance notices that every order with a discount is one cent off. A single test with three rows of input and expected output would have caught it before the merge. That is what unit tests are for at work: they let you and everyone after you change code quickly without breaking what already works. Interviewers ask about testing because it shows whether you have shipped code that other people depend on. The last lesson ended on why most teams pick Vitest over node:test. This lesson teaches testing plain JavaScript and TypeScript with Vitest. Testing React components builds on it later, in the Testing React lesson.
Why Vitest
For most of the last decade the default JavaScript test runner was Jest. It was built before ES modules and TypeScript were normal, so modern projects needed Babel or ts-jest to translate code first, and ESM support stayed awkward. Vitest is built on Vite, the same tool that runs many front-end dev servers:
- It understands TypeScript, ESM and JSX with no extra setup.
- It reuses your
vite.config.ts, so path aliases like@/lib/priceand plugins work the same in tests as in the app. - Its API is almost identical to Jest's (
describe,it,expect, mocks), so tutorials and team knowledge transfer. Most migrations are a search-and-replace ofjest.withvi.. - Watch mode is fast, because it only re-runs tests affected by the file you changed.
Vitest 5 is current at the time of writing. Check the release notes when you upgrade, because defaults do change between majors.
npm install -D vitest{
"scripts": {
"test": "vitest",
"test:ci": "vitest run --coverage"
}
}vitest on its own starts watch mode in a terminal: it runs everything, then waits and re-runs on save. vitest run runs once and exits with a non-zero code if anything failed, which is what CI needs. (Vitest also skips watch mode automatically when it detects CI, but say run explicitly so nobody has to remember that.) By default it picks up files named *.test.ts or *.spec.ts, anywhere outside node_modules.
The shape of a test
Here is a small module and its tests. Put the test file right next to the code it tests.
export type Item = { name: string; cents: number; qty: number };
export function subtotal(items: Item[]): number {
return items.reduce((sum, i) => sum + i.cents * i.qty, 0);
}
export function applyDiscount(cents: number, code: string): number {
if (code === "SAVE10") return Math.round(cents * 0.9);
if (code === "") return cents;
throw new Error(`Unknown code: ${code}`);
}import { describe, expect, it, test } from "vitest";
import { applyDiscount, subtotal } from "./price";
describe("subtotal", () => {
it("adds price times quantity", () => {
const items = [
{ name: "tea", cents: 250, qty: 2 },
{ name: "cake", cents: 400, qty: 1 },
];
expect(subtotal(items)).toBe(900);
});
it("is 0 for an empty cart", () => {
expect(subtotal([])).toBe(0);
});
});
describe("applyDiscount", () => {
test.each([
[1000, "SAVE10", 900],
[999, "SAVE10", 899], // 899.1 rounds down: the case finance cared about
[1000, "", 1000],
])("applyDiscount(%i, %s) is %i", (cents, code, expected) => {
expect(applyDiscount(cents, code)).toBe(expected);
});
it("rejects unknown codes", () => {
expect(() => applyDiscount(1000, "FREE")).toThrow("Unknown code: FREE");
});
});describegroups related tests.itandtestare the same function; pick one per codebase. A good test name reads as a sentence about behaviour: "subtotal is 0 for an empty cart".expect(value)wraps the actual result, and a matcher liketoBestates what it should be. When a matcher fails, it throws, and the runner marks that test as failed and moves on to the next.test.eachturns a table of cases into separate tests, each with its own name in the output. Use it whenever you would otherwise copy and paste a test to change one number. Edge cases (zero, negative, rounding boundaries, empty strings) are cheap to add as rows.- To check that something throws, pass a function:
expect(() => applyDiscount(...)). If you call it directly, the error is thrown beforeexpectever sees it, and the test crashes instead of passing.
Most good tests follow arrange, act, assert: set up the inputs, call the code once, check the result. If a test needs ten assertions about unrelated things, it is probably three tests.
Matchers: toBe, toEqual and toStrictEqual
The matcher you choose decides what "equal" means, and picking the wrong one is the most common reason a test passes when it should fail, or fails for no visible reason.
toBeusesObject.is: the same primitive value, or the same object in memory. Right for numbers, strings and booleans.toEqualcompares structure recursively. It ignores properties whose value isundefined, and it ignores which class an object was built from.toStrictEqualcompares structure and also checksundefinedproperties and the class.
Here is a tiny test runner that implements the three rules, so you can see that there is no magic in expect:
Press Run (⌘ Enter) to see what happens.The real Vitest gives the same seven results. Other matchers you will use daily: toBeCloseTo for floating point (0.1 + 0.2 is not toBe(0.3)), toContain for arrays and strings, toMatchObject to check only some fields of a large object, toHaveLength, toBeNull, and expect.any(String) inside an object when a value like an id or a timestamp changes every run.
{ id: 7, name: 'Ada', deletedAt: undefined }. Which assertion fails?Testing async code
This section uses async/await, which the Async JavaScript unit teaches properly. If it is new to you, skim it now and come back after The Event Loop and Promises.
Take a helper that loads a user from an API:
export async function fetchUser(id: number) {
const res = await fetch(`https://api.example.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as { id: number; name: string };
}Make the test function async and await the code. For promises that should succeed or fail, use resolves and rejects, and await them too:
import { expect, it, vi } from "vitest";
import { fetchUser } from "./user";
it("returns the parsed user", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ id: 7, name: "Ada" })),
);
vi.stubGlobal("fetch", fetchMock);
await expect(fetchUser(7)).resolves.toEqual({ id: 7, name: "Ada" });
expect(fetchMock).toHaveBeenCalledWith("https://api.example.com/users/7");
});
it("throws on a 404", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("nope", { status: 404 })));
await expect(fetchUser(1)).rejects.toThrow("HTTP 404");
});A test without await finishes before the promise settles. In older runners such a test simply passed, whatever the promise did: a test that cannot fail. Current Vitest reports an assertion that was not awaited as an error, and the @typescript-eslint/no-floating-promises lint rule catches it in the editor. Both are worth having.
Mocks, spies and stubs
A test double stands in for something your code depends on, so the test is fast, repeatable and does not send real emails or charge real cards. Vitest gives you three tools:
vi.fn()creates a fake function that records every call. You can give it behaviour:.mockReturnValue(3),.mockResolvedValue(data),.mockRejectedValue(err), or.mockImplementation(fn).vi.spyOn(object, "method")wraps an existing method so you can see its calls, and optionally replace what it returns.vi.spyOn(Math, "random").mockReturnValue(0.5)makes random code predictable.vi.mock("./module")replaces a whole module for every file that imports it in this test file.
import { expect, it, vi } from "vitest";
import { signUp } from "./signup";
import { sendEmail } from "./mailer";
vi.mock("./mailer", () => ({
sendEmail: vi.fn().mockResolvedValue("msg-1"),
}));
it("sends a welcome email", async () => {
await signUp("ada@example.com");
expect(sendEmail).toHaveBeenCalledWith("ada@example.com", "Welcome!");
});
it("does not email an invalid address", async () => {
await expect(signUp("nope")).rejects.toThrow("Invalid email");
expect(sendEmail).not.toHaveBeenCalled();
});Notice that vi.mock is written after the imports, yet signUp gets the fake mailer. Vitest hoists every vi.mock call to the very top of the file before any import runs:
Before running anything, Vitest rewrites the file and moves every vi.mock call to the top, above the imports.
That is convenient, and it has one sharp edge:
What does this print?
import { it, expect, vi } from "vitest";
import { getRate } from "./rates";
const mockRate = 1.2;
vi.mock("./rates", () => ({ getRate: vi.fn(), DEFAULT: mockRate }));
it("uses the rate", () => {});Restoring between tests
Mocks carry state: recorded calls, fake return values, replaced methods. If that state leaks from one test into the next, tests pass or fail depending on their order, which is miserable to debug. Configure clean-up once instead of remembering it in every file:
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
clearMocks: true, // wipe recorded calls before each test
restoreMocks: true, // put vi.spyOn methods back to the originals
unstubGlobals: true, // undo vi.stubGlobal (fetch, Date...)
coverage: {
provider: "v8",
include: ["src/**/*.ts"],
exclude: ["src/**/*.test.ts"],
},
},
});Recent Vitest clears call history by default, but Jest and older Vitest setups did not, so writing the options down makes the behaviour obvious to the next reader.
When mocks make tests lie
A mock is a claim about how the real thing behaves. If the claim is wrong, the test passes and production fails. Suppose you mock sendEmail to resolve, but the real one throws when the address has a plus sign. Every test is green and no welcome email ever goes out.
Rules seniors follow:
- Mock at the boundary: the network, the clock, randomness, email, payments. Do not mock your own pure functions or internal modules; call the real ones.
- Assert on results, not on calls, where you can.
expect(total).toBe(899)survives a refactor.expect(helper).toHaveBeenCalledTimes(3)breaks the moment you restructure the code, even though nothing is wrong. - If a test needs five mocks to run, the code under test has too many dependencies. That is design feedback, not a testing problem.
- For HTTP, prefer a request-level mock such as MSW (shown in Testing React) over mocking
fetchby hand, so your real request-building code is exercised too.
Match each situation to the tool.
Fake timers
Debounce, retry with backoff, session timeouts and polling all depend on time. Waiting for real seconds makes tests slow and flaky. Fake timers replace setTimeout, setInterval and Date with a clock that only moves when you tell it to. Here is the idea in miniature:
Press Run (⌘ Enter) to see what happens.The real test reads almost the same:
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { debounce } from "./debounce";
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("calls once after the user stops typing", () => {
const search = vi.fn();
const onInput = debounce(search, 300);
onInput("r"); onInput("re"); onInput("rea");
vi.advanceTimersByTime(299);
expect(search).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(search).toHaveBeenCalledTimes(1);
expect(search).toHaveBeenCalledWith("rea");
});Testing the boundary (299 then 300) is what proves the delay is right. For code that awaits promises between timers, such as a retry loop, use the async versions, await vi.advanceTimersByTimeAsync(1000), so promise callbacks get a chance to run between timer firings. vi.setSystemTime(new Date("2026-01-31")) pins "today" for date logic.
Order the steps of a test for a function that retries a failed request after 1 second.
- Tap the steps below in the right order.
Coverage, and what it does not tell you
npm install -D @vitest/coverage-v8npx vitest run --coverageThe v8 provider uses coverage data built into the JavaScript engine, so it is fast and needs no code instrumentation. The report shows, per file, the percentage of statements, branches, functions and lines that ran during the tests. Set coverage.include as in the config above. Without it, only files that some test imported appear in the report, so a module with no tests at all is invisible instead of showing 0%.
Coverage tells you what code ran, not what was checked. A test that calls every function and asserts nothing reaches 100%. Use coverage to find untested areas, especially branches like error handling, not as a score to maximise. A team rule like "coverage must not drop on a PR" is useful; "every file must hit 90%" mostly produces tests written for the number.
Snapshots: useful and harmful
expect(value).toMatchSnapshot() saves the value to a file the first time, then fails if it ever changes. toMatchInlineSnapshot() writes the value into your test file instead. Running vitest -u updates them.
Snapshots work for serialised output that should rarely change and is tedious to write by hand: a CLI's help text, generated SQL, an error message format, a config file your code produces. They are harmful for large objects or whole component trees. A 300-line snapshot does not say what matters, so when it changes, reviewers cannot tell a bug from a harmless tweak, and people press -u until it is green. If you cannot explain what a snapshot protects, write a specific assertion instead.
Environments and Browser Mode
Each test file runs in an environment. The default, node, has no DOM, which is right for logic, utilities and server code. For code that touches document or window, set environment: "jsdom" or "happy-dom" in the config (or per file with a // @vitest-environment jsdom comment at the top). Both are JavaScript imitations of a browser: fast and good enough for most component tests, but they do no real layout, so anything about sizes, scrolling or CSS is not tested.
Browser Mode runs your tests in a real browser (Chromium, Firefox or WebKit) driven by Playwright or WebdriverIO. It is stable since Vitest 4 and needs a provider package such as @vitest/browser-playwright, whose playwright() function goes in the browser.provider config option; test helpers are imported from vitest/browser. Use it when jsdom's imitation is not enough. It is slower to start, so most teams keep plain logic tests in node and use separate projects (the projects config option) for each environment.
In CI, run vitest run --coverage, and on large suites split the work across machines with --shard=1/4. Locally, vitest --changed runs only tests affected by your uncommitted changes (or by changes since a branch you name, such as --changed origin/main).
- matcher
- A method on
expect(...)such astoBeortoEqualthat states what the value should be and throws if it is not. - test.each
- Runs the same test body over a table of inputs and expected outputs, one named test per row.
- mock
- A stand-in for a real dependency that records how it was called and returns what you tell it to.
- hoisting (vi.mock)
- Vitest moving
vi.mockcalls above all imports so the fake module is in place before anything loads. - fake timers
- A replacement clock for
setTimeout,setIntervalandDatethat only moves when the test advances it. - coverage
- The share of statements, branches, functions and lines that ran during tests. It shows what ran, not what was checked.
- snapshot test
- A test that saves a serialised value and fails when it changes. Good for small stable output, bad for large trees.