开玩笑:测试Intl.DateTimeFormat [英] Jest: test Intl.DateTimeFormat

查看:220
本文介绍了开玩笑:测试Intl.DateTimeFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to test a filter function I wrote which return a date formatted using Intl.DateTimeFormat('en-GB', options):

// module "date.js"
export default function (dateISOString) {
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        timeZone: 'UTC'
    };
    let d = new Date(dateISOString);
    return new Intl.DateTimeFormat('en-GB', options).format(d);
};

这是我使用Jest进行的测试:

This is my test, using Jest:

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测试(或模拟)Intl API? 该问题似乎是由于Impl API在浏览器和Node环境中的行为不同所致.

Is it possible to test (or mock) the Intl API with Jest? It looks like the problem is due to a different behaviour of the Impl API in the browser and in a Node environment.

推荐答案

我设法找到此问题的唯一解决方案是安装

The only solution that I managed to find to this problem was to install full-icu which seemed to provide the right locales to node during the testing process.

该软件包是必需的,因为默认情况下,节点仅附带有限的语言环境集,如以下说明: https://nodejs.org/docs/latest-v9.x/api/intl.html

That package is needed because node by default only ships with a limited set of locales, explained here: https://nodejs.org/docs/latest-v9.x/api/intl.html

安装该软件包后,我必须采取的其他步骤是更改测试命令以使用:

With that package installed, the additional step that I had to take was to change my test command to use:

"test": "NODE_ICU_DATA=node_modules/full-icu jest --config jest.config.js"

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

I ran into this problem in a couple of different environments. When running the tests locally on Mac OS and also when running the tests inside a Docker container during CI.

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

Interestingly, I don't need to use the export when running the tests via WebStorm's Jest integration. It definitely seems like the behaviour of the Intl library is far from stable in node.

这篇关于开玩笑:测试Intl.DateTimeFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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