【问题标题】:How can I mock two different dates within the same function using jest?如何使用 jest 在同一个函数中模拟两个不同的日期?
【发布时间】:2021-11-16 12:30:04
【问题描述】:

这不是重复的问题。这与在同一个函数中模拟两个不同的日期有关。我尝试了以下方法来模拟日期,但将两个日期设置为相同。

  beforeAll(() => {
    Date.now = jest.fn(() => new Date('2020-04-07T10:20:30Z'));
  })

我有一个函数可以比较两个日期并返回以下天数的差异。参数 collectionDate 是 DD,例如 12 - 然后将其转换为日期,例如2022 年 12 月 1 日。

 export const getDateDifference = (collectionDate) => { // collectionDate is the DD - e.g. 12
  const today = new Date();
  const nextcollectionDate = new Date();
  nextcollectionDate.setDate(collectionDate); 

  const differenceInTime = nextcollectionDate.getTime() - today.getTime();

  return (differenceInTime / (1000 * 3600 * 24)).toFixed(0); // returns the differnce in date e.g 10 
};

我在这里遇到的问题是因为我在同一个函数中初始化了两个日期,当我模拟 Date 时,它​​们都被设置为相同的。有没有办法可以给他们两个不同的日期?或者也许我的方法不正确,我应该把它们从外面传进去?

【问题讨论】:

  • 它们只是一开始是一样的,然后你更改其中一个。这和真正的功能一样,不是吗?另请注意,您似乎没有处理today 接近月/年末的可能性,因此collectionDate下一个 月/年。一般来说,我建议不要在您的实现中直接调用 new Date()Date.now(),将时间视为依赖项(例如,请参阅 stackoverflow.com/a/65130857/3001761 了解我如何应用它)。

标签: reactjs date jestjs mocking


【解决方案1】:

你的模拟 Date.now,你真的想模拟 Date 构造函数。

const mockDate = new Date(1466424490000)
  const spy = jest
    .spyOn(global, 'Date')
    .mockImplementation(() => mockDate)

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 2020-08-26
    • 2019-04-09
    • 2019-01-06
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多