Jest setSystemTime不适用于全局作用域 [英] Jest setSystemTime not working with global scope
本文介绍了Jest setSystemTime不适用于全局作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试一个简单的减法器,它的Date属性设置为Today。
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'));
});
});
我注意到的是,模拟只能在Reducer代码中工作,但今天在其全局范围内总是返回真实日期,而不是模拟的日期。
如果我调用测试设置文件中的setSystemTime
,则today
被正确模拟。
我是不是漏掉了什么?仅为特定测试模拟全局范围内的日期的方法是什么?
如果您想签出测试回购https://github.com/dariospadoni/jestFakeTimersMock
推荐答案
发生这种情况的原因是在调用setSystemTime
之前在recucer.js
中实例化了Date
。
下面是一个如何避免这种情况的示例:
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"));
});
});
此处,一旦需要reducer.js
,将实例化Date
对象,这将是在调用setSystemTime
之后
这篇关于Jest setSystemTime不适用于全局作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文