Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the locale for `Date.prototype.toLocaleString` for Jest tests

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);
  };
like image 839
Leo Jiang Avatar asked Oct 03 '18 01:10

Leo Jiang


1 Answers

You should download the full-icu node package:

npm i full-icu --save

And run your tests like this:

NODE_ICU_DATA=node_modules/full-icu jest

So if your 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 --"`
like image 186
fabiomf Avatar answered Oct 27 '22 07:10

fabiomf