DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at thoughtsandstuff.com on

3

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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay