Stubs
Use stubs to feed canned answers to dependencies without asserting interactions.
What you'll learn
- What a stub is and how it differs from a mock
- Configuring stubbed return values and sequential answers
- When a stub is preferable to a mock
- Building reusable stub factories for common dependencies
Concept
Stubs Provide Answers
A stub is a test double whose only job is to return predetermined answers so the code under test can proceed. Unlike a mock, a stub makes no assertions about how it was called — it simply feeds data. If your test only needs the dependency to return a value and does not care about the interaction, a stub is the right tool.
Configuring Returns
In Vitest and Jest, every vi.fn() can act as a stub: mockReturnValue(42) always returns 42, mockResolvedValue(data) returns a resolved promise, and mockReturnValueOnce(a, b, c) returns a, then b, then c on successive calls. mockImplementation(fn) lets you compute the return from the arguments when a fixed value is not enough.
Stubs vs Mocks
The distinction is intent. If you write const db = { find: vi.fn().mockReturnValue(user) } and never assert on db.find, it is a stub — it exists to make the code run. If you then add expect(db.find).toHaveBeenCalledWith(id), it becomes a mock. Stubs keep tests focused on the output of the unit; mocks focus on the interactions. Over-asserting interactions leads to brittle tests, so reach for stubs first and add interaction assertions only when the interaction is the contract.
Reusable Stub Factories
When the same dependency appears in many tests, build a factory function that returns a configured stub: function stubRepo(overrides = {}) { return { findById: vi.fn().mockResolvedValue(overrides.user ?? defaultUser) } }. This keeps tests DRY and makes it obvious which values are defaults versus test-specific overrides.
In Practice
Stubs are the workhorse of unit testing because most dependencies just need to return a value for the code to proceed. When you build a stub factory, give it sensible defaults so a test can call stubRepo() with no arguments for the common case and override only the field it cares about for edge cases. Use mockResolvedValueOnce to return different values on successive calls when the code under test calls the dependency in a loop. Keep stubs small — a stub with twenty methods is a sign the interface is too wide and should be split. If a stub grows complex, consider replacing it with a fake (a real but simplified implementation) that naturally handles all the methods without per-test configuration. The goal is always the smallest double that lets the test express its intent clearly.
Example
import { describe, it, expect, vi } from "vitest";
// A stub factory for the clock dependency
function stubClock(now: Date) {
return { now: () => now };
}
describe("greeting based on time", () => {
it("says good morning before noon", () => {
const clock = stubClock(new Date("2025-01-01T08:00:00Z"));
expect(greet(clock)).toBe("Good morning");
});
it("says good evening after 6pm", () => {
const clock = stubClock(new Date("2025-01-01T19:00:00Z"));
expect(greet(clock)).toBe("Good evening");
});
});
function greet(clock: { now: () => Date }): string {
const h = clock.now().getHours();
return h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening";
}
The clock stub feeds controlled times into greet. No assertions are made on the stub itself — it exists only to make the function deterministic.
Try it
- JSON Formatter
Shape the canned data your stubs hand back to the code.
- Code Diff
Compare stubbed outputs across different test scenarios.
Common mistakes
The mistake
Adding call assertions to every stub
The fix
If you do not need to verify the interaction, leave the stub assertion-free. Excessive interaction assertions make tests brittle.
The mistake
Hardcoding stub values inline in every test
The fix
Extract a stub factory with sensible defaults and per-test overrides. This keeps tests short and the data shape consistent.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.