Testing Intl.NumberFormat in ReactJs using Jest

2020-06-16

I have a reactjs component that uses the Intl.NumberFormat class. Here's a snippet:

import * as React from "react";

export default function App({ data }) {
	function formatUnit(value) {
		return new Intl.NumberFormat("en-GB", {
			style: "unit",
			unit: "kilometer"
		}).format(value);
	}

	return (
		<div className="data-style">
			<strong>
				{formatUnit(
					data.RawValue
				)}
			</strong>
		</div>
	);
}

The above shows a snippet of a component which takes in some data and then formats that data according to the FormatUnit

I have the following test code that uses Jest:

import React from "react";
import App from "../index";
import { render } from "@testing-library/react";

describe("<App />", () => {

	let data = {
		rawValue = "1234789"
	};

	test("should match snapshot", () => {
		const { container } = render(
			<App
				data={data}
			/>
		);

		expect(container).toMatchSnapshot();
	});
});

When running this test using Jest I get the following error:

FAIL tests/index.test.js (9.51s)

	<App />

	✕ should match snapshot (102ms)

	<App /> › should match snapshot

	Error: Uncaught [RangeError: Value unit out of range for numberformat options property style]

This error is the result of using the Intl.NumberFormat library and running in NodeJs. The easiest method to resolve this error is to mock the function implementation during the beforeEach method by using jest.fn as follows:

import React from "react";
import App from "../index";
import { render } from "@testing-library/react";

describe("<App />", () => {
	let mockNumberFormatFunction = {};
	beforeEach(() => {
		const mockFormatExpression = {
			format: value => value.toString()
		};
		mockNumberFormatFunction = Intl.NumberFormat = jest
			.fn()
			.mockImplementation(() => mockFormatExpression);
	});

	afterEach(() => {
		jest.resetAllMocks();
	});

	let data = {
		rawValue = "1234789"
	};

	test("should match snapshot", () => {
		const { container } = render(
			<App
				data={data}
			/>
		);

		expect(container).toMatchSnapshot();
	});
});

By mocking out the NumberFormat functionality it ensures that the mock is called instead of the actual implementation which causes the error.