NodeJS testing datetimes with different times of the day and timezone

Viewed 817

I have a situation that places today date in DB and I use vanilla code.

const todayCloseDate = new Date().toISOString().slice(0, 10);

This obviously introduces a problem with my timezone (CST) that after 5:00 PM date becomes the next day value. I changed handling to the package data-fns (moments.js is not an option).

const todayCloseDate = DF.format(new Date(), 'yyyy-MM-dd');

It works as expected. My question is how to unit test such change? It would require to make a change in system time of a local machine what locally run tests as well in any testing environment that would run tests in CI/CD pipeline (it would CircleCI, and Jenkins).

Would to start test scenario that would cover such bug and ensure fix? My test runner is Jest.

2 Answers

Actually, setting static timezone as @Heri Hehe Setiawan would be a solution to you. With timezone frozen you could provide your tests with some edge values for dates.

Another approach may be to mock Date constructor and functions Date.parse(), Date.now() either directly providing mock or with help of some third-party components like timezone-mock.

And finally you can refer to new Date().getTimezoneOffset() to generate edge-case values:

const minuteAfterMidnightAtUTC = 
  new Date(
    new Date().setHours(
      0, -new Date().getTimezoneOffset() + 1, 0, 0
    )
  );

But we better not generate values in unit tests - it could be hard to reproduce if unit tests failed once.

When writing unit tests for Date(or Random class), you need to make sure your Date inside the test is always the same. One way to do it is by overriding it's implementation:

jest.spyOn(global.Date, 'toISOString').mockReturnValue('2011-10-05T14:48:00.000Z')// whatever date suits you;

And then write your test for this date.

Related