Skip to content

Spies

Observe 真实函数 calls 不使用 replacing 它们 using vi.spyOn and jest.spyOn.

你将学到

  • 什么 spy 是 and 如何它 differs 从 stub or mock
  • Wrapping 真实方法使用 spyOn 到 observe calls
  • Asserting call 数量, 实参, and 返回值 on spies
  • Restoring spies 到 avoid leaking 到 other 测试

概念讲解

Spies Observe

A spy wraps an existing function or method and records how it was called — arguments, return value, call count — while by default still delegating to the real implementation. This lets you verify that your code called a collaborator correctly without replacing the collaborator's behavior. Spies are ideal when the real function is safe to run but you need to confirm the interaction.

spyOn

In Vitest use vi.spyOn(对象, "方法"), in Jest jest.spyOn(对象, "方法"). The spy replaces 对象.方法 with a wrapper that records calls and forwards to the original. You can then assert with toHaveBeenCalledTimes, toHaveBeenCalledWith, and toHaveReturnedWith. If you need to change the behavior, chain .mockImplementation or .mockReturnValue on the spy.

Spies vs Mocks vs Stubs

A spy wraps real behavior and observes; a stub replaces behavior to feed answers; a mock replaces behavior and asserts expectations. Use a spy when the real function is cheap and deterministic and you mainly want to confirm it was called. Use a stub when you must change what the function returns. Use a mock when the interaction contract is the point of the test.

Cleanup

Spies mutate the object they wrap, so they leak across tests if not restored. Use vi.restoreAllMocks() or spy.mockRestore() in an afterEach to put the original method back. Without cleanup, a spy on Date.现在 in one test can silently affect every later test in the file, producing mysterious order-dependent failures.

In Practice

Spies are most valuable when you want to confirm a side effect happened without changing the behavior that produces it — for example, verifying that a service logged a warning while still letting the real logger print. When you also need to change what the spied method returns, chain .mockImplementation or .mockReturnValue onto the spy; this turns it into a hybrid that both observes and overrides. Be careful spying on methods of shared singletons or globals like console or Date, because the mutation outlives the test unless you restore it. If you find yourself spying on many methods of one object, consider whether a stub or fake would express the intent more clearly. A spy answers "做 my code call 这个, and 如何?" — reach for it when that question is the point of the test.

示例代码

              import { describe, it, expect, vi, afterEach } from "vitest";

const logger = {
  warn(message: string) {
    console.warn(message); // real implementation
  },
};

describe("cart with spy on logger", () => {
  afterEach(() => vi.restoreAllMocks());

  it("logs a warning when removing a missing item", () => {
    const spy = vi.spyOn(logger, "warn");
    const cart = new Cart(logger);
    cart.remove(999); // item does not exist
    expect(spy).toHaveBeenCalledWith(expect.stringContaining("not found"));
  });
});
            

spy wraps 真实 logger.warn 所以警告 still prints, 但测试能 也 assert 它是 called 使用正确消息. afterEach restores 原始.

动手试一试

  • Code Diff

    Compare recorded spy call 实参到 expected ones.

  • JSON Formatter

    Inspect structured 实参 spies capture.

常见错误

错误写法

Forgetting 到 restore spies

正确做法

总是添加 afterEach(() => vi.restoreAllMocks()) (or jest.restoreAllMocks) 当 using spyOn, or wrapped 方法 leaks 到 later 测试.

错误写法

Spying on 方法那个做 不 exist on 对象

正确做法

spyOn 需要属性到 already exist. 如果你 需要到 添加新 方法, use vi.fn() and assign 它, or vi.stubEnv for globals.

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误