Mocks
创建 and 验证 mocks 到 replace dependencies and assert interactions in 你的测试.
你将学到
- 如何 创建 mock 函数使用 vi.fn and jest.fn
- 设置返回值 and resolved Promise on mocks
- Asserting call 数量, 实参, and call 顺序
- Mocking 整个模块使用 vi.mock and jest.mock
概念讲解
Creating a Mock Function
A mock function is a callable that records every call made to it — its arguments, return value, and the order relative to other mocks. In Vitest use vi.fn(), in Jest jest.fn(). By default it returns undefined; you configure it with mockReturnValue, mockResolvedValue (for promises), or mockImplementation for custom logic.
Asserting Interactions
Once the code under test has run, you assert on the mock's recorded calls: toHaveBeenCalledTimes(1), toHaveBeenCalledWith(arg1, arg2), toHaveBeenLastCalledWith(...), or toHaveBeenNthCalledWith(2, ...). These assertions verify that your code interacted with its dependency correctly — the contract — without depending on the dependency's real behavior.
Mocking Modules
Sometimes you need to replace an entire imported module, like fs or an API client. vi.mock("modulePath", factory) (and jest.mock) replaces the module with your factory before any test imports it. This is powerful but hoisted — the factory runs before imports, so you cannot reference local variables in it directly. Use vi.hoisted or define the factory inline to avoid reference errors.
When to Mock
Mock at the seams where your code talks to the outside world: the filesystem, network, database, clock, or random source. Mocking your own pure functions is usually a smell — it couples the test to call sites rather than behavior. Prefer to mock the thin adapter layer and let your domain logic run for real beneath it.
In Practice
When mocking modules, remember that vi.mock is hoisted above imports — the factory runs before any import statement, so you cannot reference variables declared with const at module top level inside it. Use vi.hoisted to declare shared values that the factory can safely access. After each test, clear mock state with vi.clearAllMocks() (resets call records) or vi.resetAllMocks() (also removes implementations) so call counts and arguments never leak between tests. For partial mocks, use vi.mock with vi.importActual to keep most of a module real while replacing only the function you need. Read the failure messages carefully: a mock that was never called tells you the code took a different path than you expected, which is often the real bug rather than a test problem.
示例代码
import { describe, it, expect, vi } from "vitest";
// Mock a module before imports are evaluated
vi.mock("./api", () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 7, name: "Bo" }),
}));
import { fetchUser } from "./api";
import { getDisplayName } from "./profile";
describe("getDisplayName", () => {
it("returns the user's name from the API", async () => {
const name = await getDisplayName(7);
expect(name).toBe("Bo");
expect(fetchUser).toHaveBeenCalledWith(7);
});
});
vi.mock replaces 真实 API 模块使用 fake 谁的 fetchUser resolves immediately. 测试验证两者都 result and 那个 API 是 called 使用正确 id.
动手试一试
- JSON Formatter
格式 payloads 你的 mocked API 函数返回.
- HTTP 请求 Tester
Capture 真实请求 shape 之前 mocking 它 in 测试.
常见错误
错误写法
Referencing 外部变量内部 vi.mock factory
正确做法
vi.mock 是 hoisted above 导入, 所以外部 consts 是不 yet 定义. Use vi.hoisted(() => ...) 到 share 值 safely.
错误写法
Forgetting 到 reset mocks 之间测试
正确做法
添加 beforeEach(() => vi.clearAllMocks()) 所以 call 数量 and 实参从 one 测试做 不 leak 到下一个.
练习 Mocks
13 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。