Skip to main content

Spy on methods in `bun test`

还没翻译译自英文(bun.com)本页 5 段都还没译

Use the spyOn utility to track method calls with Bun's test runner.

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

Once you've created the spy, use it in expect assertions about method calls.

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", () => {
  expect(spy).toHaveBeenCalledTimes(0);
  leo.sayHi("pizza");
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy.mock.calls).toEqual([["pizza"]]);
});

See Mocks.

翻訳 © 2026 fanyi.dev · 原文 © 2026 the Bun project (LICENSE.md names no copyright holder) (MIT)