【发布时间】: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