开玩笑:测试 Intl.DateTimeFormat [英] Jest: test 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?问题似乎是由于浏览器和 Node 环境中 Impl API 的行为不同所致.
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.
推荐答案
我设法找到的唯一解决方案是安装 full-icu 似乎在测试过程中为节点提供了正确的语言环境.
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.
需要该包,因为默认情况下 node 只附带一组有限的语言环境,解释如下: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 库的行为在 node 中远非稳定.
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屋!