Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

reactjs - How do I set a timezone in my Jest config?

? npx jest --version
24.5.0

Got a set of jest tests that are timezone sensitive. We typically run them with an npm script: "jest": "TZ=utc jest"

With the TZ set to utc I get values like this in snapshots:

modificationDate="2019-01-08T00:00:00.000Z" 

Without it I get:

modificationDate="2019-01-08T08:00:00.000Z"

Is there a way to set that in my jest config so I can run npx jest at the command line without having to go through the NPM script? There's nothing in config docs about this.

I tried adding these two to my jest.config.js. Neither one worked:

  TZ: 'utc',

  globals: {
    TZ: 'utc',
  },

Sure, it seems trivial to work around but I'm surprised Jest doesn't have a way to configure this for tests.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This does not work on windows - see https://github.com/nodejs/node/issues/4230


The problem with process.env.TZ = 'UTC'; is, that if something runs before this line and uses Date, the value will be cached in Date. Therefore process.env is in general not suitable for setting the timezone. See https://github.com/nodejs/node/issues/3449

So a better way is to use an actual env variable, but for tests this will work:

1. Add this to your package.json

  "jest": {
     ...
     // depending on your paths it can also be './global-setup.js' 
    "globalSetup": "../global-setup.js"
  }
}

2. Put this file besides package.json as global-setup.js

module.exports = async () => {
    process.env.TZ = 'UTC';
};

3. Optional: Add a test that ensures UTC execution

describe('Timezones', () => {
    it('should always be UTC', () => {
        expect(new Date().getTimezoneOffset()).toBe(0);
    });
});

The normal setupFiles did not work for me, since they run too late (jest: ^23.5.0). So it is mandatory to use the globalSetup file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...