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

# 在 `bun test` 中监视方法

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

```ts theme={null}
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");
```

***

创建监视器后，在 `expect` 断言中使用它来验证方法调用。

```ts theme={null}
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("乌龟", () => { // [!code ++]
  expect(spy).toHaveBeenCalledTimes(0); // [!code ++]
  leo.sayHi("pizza"); // [!code ++]
  expect(spy).toHaveBeenCalledTimes(1); // [!code ++]
  expect(spy.mock.calls).toEqual([["pizza"]]); // [!code ++]
}); // [!code ++]
```

***

参见 [模拟](/test/mocks)。
