这不是一个重复的问题。这是为了模拟同一函数中的两个不同日期。我尝试过以下方法来模拟一个日期,但这会将两个日期设置为相同。
beforeAll(() => {
Date.now = jest.fn(() => new Date('2020-04-07T10:20:30Z'));
})
我有一个函数,可以比较两个日期,并返回以天为单位的差异,如下所示。参数collectionDate是DD,例如12-然后转换为日期,例如12/01/2022。
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时,它们都被设置为相同。有没有办法我可以给他们两个不同的日期?或者也许我的方法不正确,我应该把它们从外传进来?
您的mockingDate.now
,在这里您真正想要mockDate
构造函数。
const mockDate = new Date(1466424490000)
const spy = jest
.spyOn(global, 'Date')
.mockImplementation(() => mockDate)