【问题标题】:Jest setSystemTime not working with global scope开玩笑 setSystemTime 不适用于全局范围
【发布时间】: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


【解决方案1】:

它发生的原因是因为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 被调用之后

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 1970-01-01
      • 2021-09-17
      • 2019-07-08
      • 2020-07-21
      • 2019-03-14
      • 2020-12-31
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多