使用Date对象的组件在不同的时区中生成不同的快照 [英] Components using Date objects produce different snapshots in different timezones

查看:80
本文介绍了使用Date对象的组件在不同的时区中生成不同的快照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Enzyme / enzyme-to-jsonrel =nofollow noreferrer> enzyme-to-json 做我的React组件的Jest 快照测试。我正在测试 DateRange 组件的浅快照,该组件呈现具有当前范围的显示字段(例如 5/20/2016 - 7/18 / 2016 )和两个 DateInput 组件,允许选择 Date 值。这意味着我的快照包含 Date 我在 DateInput 道具和文本表示中传递给组件它解决了自己。在我的测试中,我使用 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 Dates 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).

当我在不同的时区运行我的测试时,会生成不同的快照,因为日期(年,月,...)构造函数会创建日期当地时区。例如。使用 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}

我如何制作我的测试在快照中产生相同的日期,无论它们在哪个时区运行?

How can I make my tests produce the same Dates 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)然后改变t在运行测试之前,他 TZ env var。
所以我的package.json中的脚本:

2) Then change the TZ env var before running your tests. So the script in my package.json:


  • Mac& Linux only

"test": "TZ=America/New_York react-scripts test --env=jsdom",


  • Windows

    "test": "set TZ=America/New_York && react-scripts test --env=jsdom",
    


  • 这篇关于使用Date对象的组件在不同的时区中生成不同的快照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆