gpt4 book ai didi

reactjs - Jest setSystemTime 不适用于全局范围

转载 作者:行者123 更新时间:2023-12-04 13:10:06 24 4
gpt4 key购买 nike

我正在尝试测试一个简单的 reducer ,它的日期属性设置为今天。

const today = new Date();

export const initialState = {
today
};

console.log(new Date().toDateString()); // <--- real date

export default function globalReducer(state = initialState, action) {
console.log(new Date().toDateString()); // <--- mocked date
switch (action.type) {
default:
return state;
}
}

我的基本测试
import globalReducer from "./reducer";

describe("Global reducer", () => {
beforeAll(() => {
jest.useFakeTimers("modern");
jest.setSystemTime(new Date("2021-02-18"));
});

afterAll(() => {
jest.useRealTimers();
});

it("should return the mocked date", () => {
expect(globalReducer(undefined, {}).today).toEqual(new Date('2021-02-18'));
});
});
我注意到,mock 只在reducer 代码中起作用,但今天在其全局范围内总是返回真实日期而不是模拟日期。
如果我拨打 setSystemTime在测试设置文件中,然后 today被正确 mock 。
我在这里错过了什么吗?仅针对特定测试在全局范围内模拟日期的方法是什么?
如果您想查看它,这里有一个测试仓库 https://github.com/dariospadoni/jestFakeTimersMock

最佳答案

它发生的原因是因为Daterecucer.js 中实例化之前 setSystemTime被调用。
这是一个如何避免这种情况的示例:

beforeAll(() => {
jest.setSystemTime(new Date("2021-02-18"));
});

describe("Global reducer", () => {
let globalReducer;

beforeAll(() => {
globalReducer = require("./reducer").default;
});

it("should return the mocked date", () => {
expect(globalReducer(undefined, {}).today).toEqual(new Date("2021-02-18"));
});
});
这里 Date一旦 reducer.js 对象将被实例化是必需的,这将在 setSystemTime 之后被调用

关于reactjs - Jest setSystemTime 不适用于全局范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66333024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com