Skip to content

Bun 的测试运行器支持使用 setSystemTime 函数编程设置系统时间。

ts
import { test, expect, setSystemTime } from "bun:test";

test("像 1999 年一样狂欢", () => {
  const date = new Date("1999-01-01T00:00:00.000Z");
  setSystemTime(date); // 现在是 1999 年 1 月 1 日

  const now = new Date();
  expect(now.getFullYear()).toBe(1999);
  expect(now.getMonth()).toBe(0);
  expect(now.getDate()).toBe(1);
});

setSystemTime 函数通常与 生命周期钩子 结合使用,以配置具有确定性 "假时钟" 的测试环境。

ts
import { test, expect, beforeAll, setSystemTime } from "bun:test";

beforeAll(() => {
  const date = new Date("1999-01-01T00:00:00.000Z");
  setSystemTime(date); // 现在是 1999 年 1 月 1 日
});

// 测试...

要将系统时钟重置为实际时间,请调用不带参数的 setSystemTime

ts
import { test, expect, beforeAll, setSystemTime } from "bun:test";

setSystemTime(); // 重置为实际时间

请参阅 文档 > 测试运行器 > 日期和时间 获取使用 Bun 测试运行器进行模拟的完整文档。

Bun学习网由www.bunjs.com.cn整理维护