How do I set a timezone in my Jest config?

后端 未结 3 442
无人及你
无人及你 2020-12-05 17:51
✗ 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

相关标签:
3条回答
  • 2020-12-05 18:34

    I just run into the same issue and I was able to resolve it by adding process.env.TZ = 'your/timezone'; to my jest.config.js.

    Maybe this helps in your case as well :)

    process.env.TZ = 'UTC';
    
    module.exports = {
      ...
    };
    
    0 讨论(0)
  • 2020-12-05 18:41

    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.

    0 讨论(0)
  • 2020-12-05 18:47

    If you are running tests with npm scripts, ie: npm run test, you can pass in the timezone like so:

      "scripts": {
        "test": "TZ=UTC jest"
      },
    

    I also personally feel that this (vs the process.env methods) is cleaner and easier to identify the timezone when debugging issues on remote CI servers.

    0 讨论(0)
提交回复
热议问题