如何在Jest配置中设置时区? [英] How do I set a timezone in my Jest config?

查看:78
本文介绍了如何在Jest配置中设置时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

✗ npx jest --version
24.5.0

获得了一组对时区敏感的玩笑测试.我们通常使用npm脚本运行它们:"jest": "TZ=utc jest"

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

在TZ设置为utc的情况下,我在快照中获得了这样的值:

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

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

没有它,我得到:

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

是否可以在jest配置中进行设置,以便我可以在命令行中运行npx jest而不需要通过NPM脚本?

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.

我尝试将这两个添加到我的jest.config.js中.都没有工作:

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

  TZ: 'utc',

  globals: {
    TZ: 'utc',
  },

当然,解决这个问题似乎微不足道,但令我感到惊讶的是Jest没有办法配置它进行测试.

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

推荐答案

这不适用于Windows -请参见

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

process.env.TZ = 'UTC';的问题是,如果某行在此行之前运行并使用Date,则该值将被缓存在Date中.因此process.env通常不适合设置时区.参见 https://github.com/nodejs/node/issues/3449

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

因此,更好的方法是使用实​​际的env变量,但是对于测试而言,它将起作用:

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

1.将此添加到您的package.json

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

2.将此文件放在package.json 之外,作为global-setup.js

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

3.可选:添加一个测试以确保UTC执行

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

正常的setupFiles对我不起作用,因为它们运行得太晚了(开玩笑:^ 23.5.0).因此,使用globalSetup文件是强制性.

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.

这篇关于如何在Jest配置中设置时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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