【发布时间】:2021-02-23 12:21:53
【问题描述】:
我正在尝试测试一个简单的减速器,它的日期属性设置为今天。
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 被正确模拟。
我在这里遗漏了什么吗?仅针对特定测试在全局范围内模拟日期的方式是什么?
如果你想查看它,这里有一个测试 repo https://github.com/dariospadoni/jestFakeTimersMock
【问题讨论】:
-
那是因为在调用
setSystemTime之前,日期在recucer.js中被实例化。 -
是的,但这是否意味着没有办法模拟这种情况下的日期?除非使用设置文件,但这会对所有测试产生影响
标签: reactjs unit-testing jestjs mocking react-testing-library