javascript - Jest Mocking a function implementation on a global level - Stack Overflow

I've got a utility function that looks like this:const getTimezoneString = (): string => {retu

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?

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?

Share Improve this question asked Mar 5, 2021 at 6:06 SubhanSubhan 1,6343 gold badges27 silver badges60 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

I suggest changing only the desired method of DateTimeFormat class due to possible others methods usage within an application. You can do it like so:

beforeAll(() => {
  const originalDateResolvedOptions = new Intl.DateTimeFormat().resolvedOptions();
  jest.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions').mockReturnValue({
    ...originalDateResolvedOptions,
    timeZone: 'America/Godthab',
  });
});

This overwrites only the returned timeZone property (we may of course want to overwrite more, depending on our needs)

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');
  });
});

You would need to mock the Intl class (and its methods) globally, something like:

const _global = typeof global !== 'undefined' ? global : window;

beforeAll(() => {
  _global.Intl = jest.fn(() =>
    DateTimeFormat: () => ({ resolvedOptions: () => ({ timezone: 'Africa/Nirobi' }) }));
});

afterAll(() => {
  Intl.mockClear();
});

test('it returns correct timezone string', () => {
  expect(getTimezoneString()).toEqual('Africa/Nirobi')
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745395863a4625873.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信