> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 `bun test` 中监视方法

使用 `spyOn` 工具在 Bun 的测试运行器中跟踪方法调用。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect, spyOn } from "bun:test";

const leo = {
  name: "Leonardo",
  sayHi(thing: string) {
    console.log(`Sup I'm ${this.name} and I like ${thing}`);
  },
};

const spy = spyOn(leo, "sayHi");
```

***

一旦创建了 spy，就可以用它来编写与方法调用相关的 `expect` 断言。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect, spyOn } from "bun:test";

const leo = {
  name: "Leonardo",
  sayHi(thing: string) {
    console.log(`Sup I'm ${this.name} and I like ${thing}`);
  },
};

const spy = spyOn(leo, "sayHi");

test("turtles", () => { // [!code ++]
  expect(spy).toHaveBeenCalledTimes(0); // [!code ++]
  leo.sayHi("pizza"); // [!code ++]
  expect(spy).toHaveBeenCalledTimes(1); // [!code ++]
  expect(spy.mock.calls).toEqual([["pizza"]]); // [!code ++]
}); // [!code ++]
```

***

完整的 Bun 测试运行器模拟文档，请参见 [文档 > 测试运行器 > 模拟](/test/mocks)。
