Set moment timezone in Jest tests

为君一笑 提交于 2021-01-26 11:04:29

问题


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?


回答1:


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"
  },



回答2:


This worked for me

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

but ensure "moment-timezone": "^0.5.27" is installed in your npm dependencies



来源:https://stackoverflow.com/questions/56274496/set-moment-timezone-in-jest-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!