We have front-end engineers around the world, so when we run Date.prototype.toLocaleString
, we get different results. Sometimes, these differences show up in Jest tests. If someone in a different country runs a Jest test, it may fail because of toLocaleString
. What are some ways to force Jest to use a certain locale?
As a bandaid solution, I added the following to the failing tests:
const toLocaleString = Date.prototype.toLocaleString;
// eslint-disable-next-line no-extend-native
Date.prototype.toLocaleString = function(locale = 'en-US', ...args) {
return toLocaleString.call(this, locale, ...args);
};
We have front-end engineers around the world, so when we run Date.prototype.toLocaleString
, we get different results. Sometimes, these differences show up in Jest tests. If someone in a different country runs a Jest test, it may fail because of toLocaleString
. What are some ways to force Jest to use a certain locale?
As a bandaid solution, I added the following to the failing tests:
const toLocaleString = Date.prototype.toLocaleString;
// eslint-disable-next-line no-extend-native
Date.prototype.toLocaleString = function(locale = 'en-US', ...args) {
return toLocaleString.call(this, locale, ...args);
};
Share
Improve this question
asked Oct 3, 2018 at 1:38
Leo JiangLeo Jiang
26.1k58 gold badges176 silver badges327 bronze badges
2
- Since you just need to adjust for testing, it's better to change system locale before testing. – Alan haha Commented Oct 3, 2018 at 2:57
-
1
I think this is okay. You are already mocking the date itself. Another mon scenario is to mock
Date.now
. So I think this is not such a "bandaid" solution after all. – Herman Starikov Commented Oct 4, 2018 at 19:38
1 Answer
Reset to default 11You should add full-icu
to your dev dependencies:
npm i full-icu --save-dev
And run your tests like this:
NODE_ICU_DATA=node_modules/full-icu jest
So if you're running a npm script you package.json will look like this:
"scripts": {
"dev": "...",
"test": "NODE_ICU_DATA=node_modules/full-icu jest",
},
In case of using React Scripts:
"scripts": {
"dev": "...",
"test": "NODE_ICU_DATA=node_modules/full-icu react-scripts test",
},
And if you are using Jest VSCode extension you'll have to change this configuration:
`"jest.pathToJest": "npm run test --"`