Skip to content

Stubs

Use stubs 到 feed canned 答案到 dependencies 不使用 asserting interactions.

你将学到

  • 什么 stub 是 and 如何它 differs 从 mock
  • 配置 stubbed 返回值 and sequential 答案
  • 当 stub 是 preferable 到 mock
  • 构建 reusable stub factories for 常见 dependencies

概念讲解

Stubs Provide Answers

stub 是一种 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(数据) returns a resolved promise, and mockReturnValueOnce(, 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: 函数 stubRepo(overrides = {}) { 返回 { findById: vi.fn().mockResolvedValue(overrides.用户 ?? 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.

示例代码

              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";
}
            

clock stub feeds controlled 次数到 greet. 否 assertions 是制作 on stub 它自己 — 它 exists 仅到 制作函数 deterministic.

动手试一试

  • JSON Formatter

    Shape canned 数据你的 stubs hand 后面到 code.

  • Code Diff

    Compare stubbed 输出跨越不同测试场景.

常见错误

错误写法

添加 call assertions 到每个 stub

正确做法

如果你 做不 需要到 验证 interaction, leave stub assertion-free. Excessive interaction assertions 制作测试 brittle.

错误写法

Hardcoding stub 值 inline in 每个测试

正确做法

Extract stub factory 使用 sensible defaults and 每-测试 overrides. 这个 keeps 测试短 and 数据 shape consistent.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误