Jest setSystemTime 不适用于全局范围

Jest setSystemTime not working with global scope

我正在尝试测试一个日期 属性 设置为今天的简单减速器。

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 代码中起作用,但今天在其全局范围内始终 returns 真实日期而不是模拟日期。

如果我在测试设置文件中调用 setSystemTime,那么 today 会被正确模拟。

我是不是漏掉了什么?仅针对特定测试在全局范围内模拟日期的方法是什么?

如果您想查看,这里有一个测试仓库 https://github.com/dariospadoni/jestFakeTimersMock

它发生的原因是因为 Date 在调用 setSystemTime 之前在 recucer.js 中实例化。

这是一个如何避免这种情况的示例:

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 之后

就我而言,它在 fakeAsync 函数内部不起作用。当我控制日志时,我一直看到真实的日期。从 fakeAsync 中删除测试,我可以看到模拟日期。