How to mock and test Intl.DateTimeFormat in Jest

Intl.DateTimeFormat provides powerful functionalities to format dates.

This article demonstrates how to mock and test Intl.DateTimeFormat with Jest.

Example

Consider we have the following function that does format a given date into parts:

export const formatDateTimeToParts = (
  date,
  locale = "en-US",
  options = {
    month: "short",
    day: "numeric"
  }
) => {
  const dateTimeFormat = new Intl.DateTimeFormat(locale, options);
  const parts = dateTimeFormat.formatToParts(date);
  const dateTimeParts = {};
  parts.forEach((part) => {
    dateTimeParts[part.type] = part.value;
  });

  return dateTimeParts;
};

To use the above function, we can call it and pass at least the required parameter which is the first argument date, other parameters locale, and options are optional.

const formattedDate = formatDateTimeToParts(new Date());
console.log(JSON.stringify(formattedDate));

// Output:
// {"month":"Oct","literal":" ","day":"26"}

How to mock and test Intl.DateTimeFormat in Jest

We need to mock the implementation of Intl.DateTimeFormat by spying on any call to Intl.DateTimeFormat function, then we are going to return our mocked implementation.

In other words, we will add a listener to the DateTimeFormat calls, and once it’s called we will return our mocked implementation, as shown below:

const { DateTimeFormat } = Intl;
jest.spyOn(Intl, "DateTimeFormat")
  .mockImplementation(
   (locale, options) => new DateTimeFormat(locale, options)
  );

Then we can add our test implementation to verify our implementation:

  test("formatDateTimeToParts", () => {
    // Create a new data - note the month is zero indexed
    // 2022-08-15
    const currentDate = new Date(2022, 7, 15);
    const result = formatDateTimeToParts(currentDate, "en-US", {
      day: "2-digit",
      month: "long",
      year: "numeric"
    });

    expect(result).toStrictEqual({
      month: "August",
      literal: ", ",
      day: "15",
      year: "2022"
    });
  });

In the above test suite, we have created a new date object new Date(2022, 7, 15), Then we passed it along with the locale and format options to the formatDateTimeToParts function and we did verify the output of the function results.


Source code


Photo from Unsplash

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: