Jest Mocking a function implementation on a global level

I’ve got a utility function that looks like this:

const getTimezoneString = (): string => {
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
};

Since this function is part of an app that would run on multiple new/old browsers, I wanted to test the Intl support for different platforms.

I’m looking for a way to globally define a mock implementation of the Intl object so that when I do something like:

expect(getTimezoneString()).toEquall("Africa/Nirobi")

similarly, I would change the timeZone in the implementation and test if my function returns the new timezone.

I would also like to test, what happens if the Intl object is not supported by the browser. i.e returning undefined or throwing an error probably.

I’ve been using jest mockImplementation method to create a mock that returns the desired output:

const IntlDateTimeFormatMock = jest
      .fn(Intl.DateTimeFormat)
      .mockImplementation(() => undefined);

Is there a way I can get this mock function to automatically replace the output of the Intl whenever I call my utility?

Answer

For anyone going through the same problem, this is how I ended up doing it:

describe('My Utility - getTimezoneString', () => {
  const originalIntl = Intl;

  beforeEach(() => {
    global.Intl = originalIntl;
  });

  afterAll(() => {
    global.Intl = originalIntl;
  });

  it('should return Africa/Nirobi', () => {
    global.Intl = {
      DateTimeFormat: () => ({
        resolvedOptions: jest
          .fn()
          .mockImplementation(() => ({ timeZone: 'Africa/Nirobi' })),
      }),
    } as any;

    expect(getTimezoneString()).toEqual('Africa/Nirobi');
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *