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

Last Updated:
Unit testing localizations for React app

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?

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
  }
}

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;
}

And now all of the unit tests pass!

Related Posts

Get helpful Jest Pieces right to your inbox

Keep up to date with all helpful bits of Jest snippets and articles.