简体   繁体   English

如何在 Create React App 的 jest config 中设置时区?

[英]How do I set the timezone in jest config in Create React App?

I wrote some tests in my Create React App application that passed locally but failed in CI due to differences in timezone.我在我的 Create React App 应用程序中编写了一些测试,这些测试在本地通过但由于时区差异在 CI 中失败。 So I need a way to set the timezone to UTC for all tests in my application.所以我需要一种方法来为我的应用程序中的所有测试设置时区为 UTC。 I tried the suggestions on this question , but they didn't work, likely due to Create React App:我尝试了关于这个问题的建议,但它们没有奏效,可能是由于 Create React App:

Things that I have tried:我尝试过的事情:

  • changing test script from react-scripts test to TZ=UTC && react-scripts test将测试脚本从react-scripts test更改为TZ=UTC && react-scripts test
  • Adding the following snippet to setupTests.js:将以下代码段添加到 setupTests.js:
module.exports = async () => {
    process.env.TZ = 'UTC';
};

It should be "test": "TZ=UTC react-scripts test", (without &&).它应该是"test": "TZ=UTC react-scripts test", (没有&&)。

Note that it's working only when you run it from the terminal (because I'm running sometimes tests from IDE and then you have to change it separate in IDE tests config).请注意,它仅在您从终端运行时才有效(因为我有时会从 IDE 运行测试,然后您必须在 IDE 测试配置中单独更改它)。

I'll add this as an answer even though one has already been accepted.即使已经接受了一个答案,我也会将其添加为答案。

All you're trying to do is mock something, as you've pointed out.正如您所指出的,您所要做的就是模拟某些东西。 All you need to do is just make it a little bit easier to mock.您需要做的只是让它更容易模拟。

If you had a function like this:如果您有这样的 function:

const formatTime = (time) => new Date(time).toLocaleString()

Then just modify it to look like this:然后只需将其修改为如下所示:

const formatTime = (time, timezone) => new Date(time).toLocaleString(timezone)

and voila.瞧。 Testing this becomes trivial because now you can just pass in an argument to your function to verify it's functionality.对此进行测试变得微不足道,因为现在您只需将参数传递给 function 即可验证其功能。 No messing with testing environments or anything.没有弄乱测试环境或任何东西。 Can't get much easier than testing a pure function.没有比测试纯函数更容易的了。

You don't need to test that toLocaleString uses the default time zone when non is supplied because that's not your code - it's a spec that you are adhering to.您无需测试toLocaleString是否在提供 non 时使用默认时区,因为那不是您的代码 - 这是您遵守的规范。

For a cross-platform solution, you can create a .env.test (if not already created) file and add TZ=UTC to the environment variables there.对于跨平台解决方案,您可以创建一个.env.test (如果尚未创建)文件并将TZ=UTC添加到那里的环境变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM