Skip to main content
bun:test 允许你在测试中更改当前时间。 这适用于以下任意一种情况:
  • Date.now
  • new Date()
  • new Intl.DateTimeFormat().format()

setSystemTime

要更改系统时间,请使用 setSystemTime
test.ts
Jest 的 useFakeTimersuseRealTimers 也受支持,因此使用它们的现有测试可以继续正常运行:
test.ts

重置系统时间

要重置系统时间,请调用 setSystemTime 并不传入参数:
test.ts

使用 jest.now() 获取模拟时间

当时间被模拟时(通过 setSystemTimeuseFakeTimers),jest.now() 会返回当前模拟的时间戳:
test.ts
使用它可以读取模拟时间,而无需创建新的 Date 对象。

设置时区

默认情况下,bun test 在 UTC (Etc/UTC) 时区运行。要更改时区,可以将 TZ 环境变量传递给 bun test
terminal
或者在运行时设置 process.env.TZ
test.ts
与 Jest 不同,你可以在运行时多次更改时区。