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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: