Set moment timezone in Jest tests
Asked Answered
I

2

15

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?

Isaiasisak answered 23/5, 2019 at 11:43 Comment(2)
Maybe How to mock moment.utc() for unit tests? can be useful to you.Metanephros
If anyone needs a solution for that problem I can recommend timezone-mock lib - npmjs.com/package/timezone-mock.Isaiasisak
L
29

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"
  },
Lustreware answered 4/10, 2019 at 6:48 Comment(2)
Does it work on Windows machines? I tried this but It didn't work.Censor
@DanielNguyen no, this one doesn't work on Windows in Node versions lower than 17. More info here: github.com/nodejs/node/issues/4230Germanium
P
4

If you wish to set that timezone for all test files, setting the TZ environment should be enough but if you're looking for setting the timezone for a single test file, the following should be enough

import moment from 'moment-timezone'
moment.tz.setDefault('America/New_York')

https://momentjs.com/timezone/docs/#/using-timezones/default-timezone/

Parental answered 12/7, 2022 at 19:41 Comment(2)
This works for test cases in windows and there is no need to add env var.Krissie
Ensure to use import moment from moment-timezone in your main code too lol. I was using moment at firstCaftan

© 2022 - 2024 — McMap. All rights reserved.