bun:test 允许你在测试中更改当前时间。
这适用于以下任意一种情况:
Date.nownew Date()new Intl.DateTimeFormat().format()。
setSystemTime
要更改系统时间,请使用setSystemTime:
test.ts
useFakeTimers 和 useRealTimers 也受支持,因此使用它们的现有测试可以继续正常运行:
test.ts
重置系统时间
要重置系统时间,请调用setSystemTime 并不传入参数:
test.ts
使用 jest.now() 获取模拟时间
当时间被模拟时(通过setSystemTime 或 useFakeTimers),jest.now() 会返回当前模拟的时间戳:
test.ts
Date 对象。
设置时区
默认情况下,bun test 在 UTC (Etc/UTC) 时区运行。要更改时区,可以将 TZ 环境变量传递给 bun test:
terminal
process.env.TZ:
test.ts
与 Jest 不同,你可以在运行时多次更改时区。