Skip to main content

日期

日期是不可预测的。

为了让包含日期的 SUT 变得稳定,可预测。

比如我们要测试下面的函数,

export function checkSunday(): string {
const today = new Date();

if (today.getDay() === 0) {
return "happy";
} else {
return "sad";
}
}

上面函数的测试要如何写呢,日期每天都在变化,这意味着测试经常都需要维护。

这时候,我们可以使用 vi.setSystemTime(date) API 来 stub 日期。

it("should be happy when it's Sunday", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2024, 1, 14));

const result = checkSunday();

expect(result).toBe("happy");
vi.useRealTimers();
});

可以在 beforeEachafterEach 中,使用 vi.useFakeTimers()vi.useRealTimers() 来将日期重置。