-1

This isn't a duplicate question. This is to do with mocking two different dates within the same function. I have tried the following approach to mock a date but that sets both dates to be the same.

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

I have a function which compares two dates and return the difference in days as following. The parameter collectionDate is the DD e.g.12 - which is then converted into the date e.g. 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 
};

The issue I am having here is because I have two dates being initialised within the same function, when I mock Date, they both get set to the same. Is there a way I can give them both a different date? Or maybe my approach is incorrect and I should instead pass them in from out?

coding1223322
  • 461
  • 11
  • 26
  • They're only both the same to start with, then you _change_ one of them. That's the same as the real functionality, no? Also note you don't seem to be dealing with the possibility that `today` is near the end of the month/year and the `collectionDate` is therefore in the _next_ month/year. In general I'd recommend not directly calling `new Date()` or `Date.now()` in your implementation at all, treat time as a dependency (see e.g. https://stackoverflow.com/a/65130857/3001761 for how I've applied that). – jonrsharpe Nov 16 '21 at 13:41

1 Answers1

0

Your mocking Date.now, where you really want to mock the Date constructor.

const mockDate = new Date(1466424490000)
  const spy = jest
    .spyOn(global, 'Date')
    .mockImplementation(() => mockDate)
Steve -Cutter- Blades
  • 5,057
  • 2
  • 26
  • 40