Skip to content

bun:test 允许你更改测试中的时间。

这适用于以下任何情况:

  • Date.now
  • new Date()
  • new Intl.DateTimeFormat().format()

NOTE

计时器尚未受到影响,但可能在 Bun 的未来版本中实现。

setSystemTime

要更改系统时间,请使用 setSystemTime

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

beforeAll(() => {
  setSystemTime(new Date("2020-01-01T00:00:00.000Z"));
});

test("现在是 2020 年", () => {
  expect(new Date().getFullYear()).toBe(2020);
});

为了支持使用 Jest 的 useFakeTimersuseRealTimers 的现有测试,你可以使用 useFakeTimersuseRealTimers

ts
test("就像在 jest 中一样", () => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date("2020-01-01T00:00:00.000Z"));
  expect(new Date().getFullYear()).toBe(2020);
  jest.useRealTimers();
  expect(new Date().getFullYear()).toBeGreaterThan(2020);
});

test("与 jest 不同", () => {
  const OriginalDate = Date;
  jest.useFakeTimers();
  if (typeof Bun === "undefined") {
    // 在 Jest 中,Date 构造函数会改变
    // 这可能导致各种错误,因为突然 Date !== Date 在测试之前。
    expect(Date).not.toBe(OriginalDate);
    expect(Date.now).not.toBe(OriginalDate.now);
  } else {
    // 在 bun:test 中,当你使用 useFakeTimers 时,Date 构造函数不会改变
    expect(Date).toBe(OriginalDate);
    expect(Date.now).toBe(OriginalDate.now);
  }
});

重置系统时间

要重置系统时间,请不传递参数给 setSystemTime

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

test("曾经是 2020 年,但只是一瞬间。", () => {
  // 设置为某个时间!
  setSystemTime(new Date("2020-01-01T00:00:00.000Z"));
  expect(new Date().getFullYear()).toBe(2020);

  // 重置它!
  setSystemTime();

  expect(new Date().getFullYear()).toBeGreaterThan(2020);
});

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

当你使用模拟时间(使用 setSystemTimeuseFakeTimers)时,你可以使用 jest.now() 获取当前模拟时间戳:

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

test("获取当前模拟时间", () => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date("2020-01-01T00:00:00.000Z"));

  expect(Date.now()).toBe(1577836800000); // 2020 年 1 月 1 日时间戳
  expect(jest.now()).toBe(1577836800000); // 相同的值

  jest.useRealTimers();
});

当你需要直接访问模拟时间而不创建新的 Date 对象时,这很有用。

设置时区

默认情况下,所有 bun test 运行的时区都设置为 UTC(Etc/UTC),除非被覆盖。要更改时区,可以将 $TZ 环境变量传递给 bun test

bash
TZ=America/Los_Angeles bun test

或者在运行时设置 process.env.TZ

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

test("欢迎来到加利福尼亚!", () => {
  process.env.TZ = "America/Los_Angeles";
  expect(new Date().getTimezoneOffset()).toBe(420);
  expect(new Intl.DateTimeFormat().resolvedOptions().timeZone).toBe("America/Los_Angeles");
});

test("欢迎来到纽约!", () => {
  // 与 Jest 不同,你可以在运行时多次设置时区,它会正常工作。
  process.env.TZ = "America/New_York";
  expect(new Date().getTimezoneOffset()).toBe(240);
  expect(new Intl.DateTimeFormat().resolvedOptions().timeZone).toBe("America/New_York");
});

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