简体   繁体   中英

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. So I need a way to set the timezone to UTC for all tests in my application. I tried the suggestions on this question , but they didn't work, likely due to Create React App:

Things that I have tried:

  • changing test script from react-scripts test to TZ=UTC && react-scripts test
  • Adding the following snippet to setupTests.js:
module.exports = async () => {
    process.env.TZ = 'UTC';
};

It should be "test": "TZ=UTC react-scripts test", (without &&).

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).

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:

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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