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
使用getApiDateFormat
由moment.tz.setDefault("America/New_York")
但是,我所有的尝试都失败了,因为他们有没有影响moment
LIB采用进口getApiDateFormat
。)
How to solve such a problem and test it properly?
(如何解决此类问题并进行正确测试?)
ask by yqbk translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…