使用 Date 对象的组件在不同的时区产生不同的快照 [英] Components using Date objects produce different snapshots in different timezones
问题描述
我正在使用 Enzyme 和 酶到 json 做 Jesta> 我的 React 组件的快照测试.我正在测试 DateRange
组件的浅层快照,该组件使用当前范围(例如 5/20/2016 - 7/18/2016
)和两个 <允许选择 Date
值的 code>DateInput 组件.这意味着我的快照包含我在 DateInput
道具和它自己解析的文本表示中传递给组件的 Date
.在我的测试中,我使用 new Date(1995, 4, 23)
创建了一些固定日期.
I'm using Enzyme with enzyme-to-json to do Jest snapshot testing of my React components. I'm testing shallow snapshots of a DateRange
component that renders a display field with the current range (e.g. 5/20/2016 - 7/18/2016
) and two DateInput
components that allow selecting a Date
value. This means that my snapshot contains the Date
s I pass to the component both in the DateInput
props and in a text representation it resolves itself. In my test I'm creating some fixed dates using new Date(1995, 4, 23)
.
当我在不同的时区运行我的测试时,这会产生不同的快照,因为 Date(year, month, ...)
构造函数在本地创建日期时区.例如.使用 new Date()
会在我的本地时区和我们的 CI 服务器上运行的快照之间产生这种差异.
When I run my test in different timezones, this produces different snapshots, because the Date(year, month, ...)
constructor creates the date in the local timezone. E.g. use of new Date()
produces this difference in snapshot between runs in my local timezone and on our CI server.
- value={1995-05-22T22:00:00.000Z}
+ value={1995-05-23T00:00:00.000Z}
我尝试从日期中删除时区偏移量,但随后快照的显示字段值有所不同,其中使用了与本地时区相关的表示.
I tried removing the timezone offset from the dates, but then the snapshot differed in the display field value, where the local timezone-dependent representation is used.
- value={5/20/2016 - 7/18/2016}
+ value={5/19/2016 - 7/17/2016}
如何让我的测试在快照中产生相同的Date
,而不管它们运行在哪个时区?
How can I make my tests produce the same Date
s in snapshots regardless of the timezone they're run in?
推荐答案
我为此苦苦挣扎了几个小时/几天,但只有这个对我有用:
I struggled with this for hours/days and only this worked for me:
1) 在您的测试中:
Date.now = jest.fn(() => new Date(Date.UTC(2017, 7, 9, 8)).valueOf())
2) 然后在运行测试之前更改 TZ
环境变量.所以我的 package.json 中的脚本:
2) Then change the TZ
env var before running your tests.
So the script in my package.json:
(仅限 Mac 和 Linux)
"test": "TZ=America/New_York react-scripts test --env=jsdom",
(Windows)
"test": "set TZ=America/New_York && react-scripts test --env=jsdom",
这篇关于使用 Date 对象的组件在不同的时区产生不同的快照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!