如何在我的 Jest 配置中设置时区? [英] How do I set a timezone in my Jest config?
问题描述
✗ npx jest --version24.5.0
有一组对时区敏感的笑话测试.我们通常使用 npm 脚本运行它们:"jest": "TZ=utc jest"
将 TZ 设置为 utc 后,我在快照中得到如下值:
modificationDate="2019-01-08T00:00:00.000Z"
没有它我得到:
modificationDate="2019-01-08T08:00:00.000Z"
有没有办法在我的 jest 配置中设置它,这样我就可以在命令行中运行 npx jest
而无需通过 NPM 脚本?配置文档关于这个.
我尝试将这两个添加到我的 jest.config.js.没有一个工作:
TZ: 'utc',全局变量:{TZ: 'UTC',},
当然,解决这个问题似乎微不足道,但我很惊讶 Jest 没有办法为测试配置它.
这在节点 17.0.1 之前的 Windows 上不起作用 - 请参阅 https://github.com/nodejs/node/issues/4230
process.env.TZ = 'UTC';
的问题是,如果在此行之前运行并使用 Date
,该值将被缓存在 <代码>日期代码>.因此process.env
一般不适合设置时区.请参阅https://github.com/nodejs/node/issues/3449>
所以更好的方法是使用实际的 env 变量,但对于测试,这将起作用:
1.将此添加到您的 package.json
玩笑":{...//根据你的路径,它也可以是 './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('应该总是UTC', () => {期望(新日期().getTimezoneOffset()).toBe(0);});});
普通的setupFiles
对我来说不起作用,因为它们运行得太晚了(笑话:^23.5.0).因此,强制使用 globalSetup 文件.
✗ 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.
This does not work on windows prior to node 17.0.1 - 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.
这篇关于如何在我的 Jest 配置中设置时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!