Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

javascript - 在Jest测试中设置时刻时区(Set moment timezone in Jest tests)

I have the util function that is parsing given date (ie '2019-01-28') in specific date format and then using momentJS retrieving beginning of that day and converting it to ISO date format:(我有util函数,它以特定的日期格式解析给定的日期(即“ 2019-01-28”),然后使用momentJS检索当天的开始并将其转换为ISO日期格式:)

dates.js(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.(我想使用Jest测试此功能,并moment设置特定时区以独立于我的位置使用这些测试。) For now, I have:(现在,我有:) dates.test.js(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.(由于我目前位于Europe/Warsaw时区。) 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 .(我试着使用jest.mock更换moment使用getApiDateFormatmoment.tz.setDefault("America/New_York")但是,我所有的尝试都失败了,因为他们有没有影响moment LIB采用进口getApiDateFormat 。) How to solve such a problem and test it properly?(如何解决此类问题并进行正确测试?)   ask by yqbk translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use TZ env var...(使用TZ变量...)

You can prepend to your package.json so all machines run with the same timezone like so:(您可以在package.json前缀,以便所有计算机都在相同的时区运行,如下所示:) "scripts": { "test": "TZ=UTC jest", "coverage": "TZ=UTC jest --coverage" },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...