Search code examples
javascriptdatemockingjestjsmomentjs

Set moment timezone in Jest tests


I have the util function that is parsing given date (i.e. '2019-01-28') in specific date format and then using momentJS retrieving beginning of that day and converting it to ISO date format:

dates.js

import moment from 'moment'

export const getApiDateFormat = (date, dateFormat = getLocaleDateString()) =>
    moment(date, dateFormat)
      .startOf('day')
      .toISOString()

I would like to test this function using Jest and set the specific timezone for moment to use those tests independent of my location.

For now, I have:

dates.test.js

const formattedDate = '2019-01-27T23:00:00.000Z'

test('date in russian format - 28.01.2019', () => {
      const russianDateFormat = 'DD.MM.YYYY'
      expect(getApiDateFormat('28.01.2019', russianDateFormat)).toEqual(
        formattedDate,
      )
    })

since I'm currently located in Europe/Warsaw timezone. How to make this test location independent?

I've tried to use jest.mock to replace moment used by getApiDateFormat by moment.tz.setDefault("America/New_York"), however, all my attempts have failed since they have no influence on moment lib imported by getApiDateFormat.

How to solve such a problem and test it properly?


Solution

  • Use TZ env var...

    You can prepend to your package.json so all machines run with the same timezone like so:

      "scripts": {
        "test": "TZ=UTC jest",
        "coverage": "TZ=UTC jest --coverage"
      },