Javascript 笑话:测试Intl.DateTimeFormat

Javascript 笑话:测试Intl.DateTimeFormat,javascript,jestjs,datetime-format,Javascript,Jestjs,Datetime Format,我想测试我编写的一个过滤器函数,它返回使用Intl.DateTimeFormat('en-GB',options'格式化的日期): 这是我的测试,用笑话: import date from '@/filters/date'; describe('date', () => { it('should format the date into dd/mm/yyyy', () => { expect(date('2014-02-11')).toEqual('11/02

我想测试我编写的一个过滤器函数,它返回使用Intl.DateTimeFormat('en-GB',options'格式化的日期):

这是我的测试,用笑话:

import date from '@/filters/date';
describe('date', () => {
    it('should format the date into dd/mm/yyyy', () => {
        expect(date('2014-02-11')).toEqual('11/02/2014');
    });
});
但它在以下方面失败了:

Expected value to equal:
  "11/02/2014"
Received:
  "02/11/2014"
可以用Jest测试(或模拟)INTLAPI吗?
问题似乎是由于Impl API在浏览器和节点环境中的不同行为造成的。

我找到的解决此问题的唯一方法是安装一个在测试过程中似乎为节点提供了正确的区域设置的软件

之所以需要该包,是因为默认情况下,node只附带一组有限的区域设置,如下所述:

安装该软件包后,我必须采取的额外步骤是将我的测试命令更改为使用:

“测试”:“NODE\u ICU\u DATA=NODE\u modules/full ICU jest--config jest.config.js”

我在几个不同的环境中遇到了这个问题。在Mac OS上本地运行测试时,以及在CI期间在Docker容器内运行测试时


有趣的是,当通过WebStorm的Jest集成运行测试时,我不需要使用导出。显然,Intl库的行为在节点中远远不稳定。

如前所述,您可以使用polyfill


package.json中添加
intl

 "intl": "*",
在jest.config.js中

module.exports = {
    moduleNameMapper: {
        Intl: '<rootDir>/node_modules/intl/'
    }
};
 describe(`Date by locale`, () => {
     beforeAll(() => {  global.Intl = require('intl'); });
    // Add your tests here. 
    // Add a temporary console.log to verify the correct output
 }

你让我开心!如果您的操作系统已经提供了完整的icu,您可以跳过安装。例如,在Mac OS上,您可能在/usr/share/icu中有一个icudt*.dat文件,因此您可以将测试脚本设置为
“NODE\u icu\u DATA=/usr/share/icu jest…”
@JasonRice,这是在Linux(bash)和类似系统上设置环境变量的语法。React人员在其他shell中有一系列设置变量。也许可以尝试
“测试”:“设置\“节点\u ICU\u数据=节点\u模块/完整ICU\”&&jest…”
。感谢链接,但知道如何在这两种环境下进行测试总是很好的,尤其是在发布时。我最终只是使用了命令前面的npm交叉环境。这似乎工作得很好,不需要额外的配置。为了使它在windows/linux上都能工作,我使用了cross env package:关于它如何工作的更多信息:很好,但不推荐这对我在Node 15中工作,其中
“test”:“Node\u ICU\u DATA=Node\u modules/full ICU jest--config jest.config.js”
没有
module.exports = {
    moduleNameMapper: {
        Intl: '<rootDir>/node_modules/intl/'
    }
};
 describe(`Date by locale`, () => {
     beforeAll(() => {  global.Intl = require('intl'); });
    // Add your tests here. 
    // Add a temporary console.log to verify the correct output
 }