DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at thoughtsandstuff.com on

Unit Testing Localization in React App. Solution for Mocking Intl API

Are you adding localization to your app and trying to test it with Jest unit tests and React Testing Library?

Are you using the Intl Internationalization API and running into problems mocking it?


This article was originally posted (and is more up to date) at https://thoughtsandstuff.com/unit-testing-localizations-in-react-app-solution-for-mocking-intl-api/


I have recently been working on an app that used the Intl.DateTimeFormat and Intl.NumberFormat functions. Adding localization to an app is a fairly substantial feature. It effects ALL users and it makes sense to make sure that all components and functions are properly tested.

There were several articles that said using IntlPolyfill would do the job.

The advice was import the polyfill into the test-utils.js file like so:

// test-utils.js
import IntlPolyfill from 'intl'
import 'intl/locale-data/jsonp/pt'

export const setupTests = () => {
  if (global.Intl) {
    Intl.NumberFormat = IntlPolyfill.NumberFormat
    Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat
  } else {
    global.Intl = IntlPolyfill
  }
}
Enter fullscreen mode Exit fullscreen mode

This worked for testing localized currencies and number formatting. However I could not use timezone string except in UTC. When trying to unit test functions using the Intl.NumberFormat API it produced this error:

RangeError: timeZone is not supported.

Turns out that the IntlPolyfill only does half the job, and Node doesn’t support time zones.

The Solution

The solution was to use the IntlPolyfill alongside the date-time-format-timezone package like this:

// test-utils.js
import IntlPolyfill from 'intl'
import DateTimeFormatTimezonePolyfill from 'date-time-format-timezone';
import 'intl/locale-data/jsonp/pt'

if (global.Intl) {
    Intl.NumberFormat = IntlPolyfill.NumberFormat;
    Intl.DateTimeFormat = DateTimeFormatTimezonePolyfill;
} else {
    global.Intl = IntlPolyfill;
}
Enter fullscreen mode Exit fullscreen mode

And now all of the unit tests pass!

Top comments (0)