【问题标题】:Jest Mocking a function implementation on a global levelJest 在全局级别模拟函数实现
【发布时间】:2021-03-05 06:06:16
【问题描述】:

我有一个如下所示的实用函数:

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

由于此功能是可在多个新/旧浏览器上运行的应用程序的一部分,因此我想测试 Intl 对不同平台的支持。

我正在寻找一种方法来全局定义 Intl 对象的模拟实现,以便当我执行以下操作时:

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

同样,我会在实现中更改时区并测试我的函数是否返回新时区。

我还想测试一下,如果浏览器不支持 Intl 对象会发生什么。即可能返回未定义或抛出错误。

我一直在使用 jest mockImplementation 方法来创建一个返回所需输出的模拟:

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

有没有办法让这个模拟函数在我调用我的实用程序时自动替换 Intl 的输出?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    您需要在全局范围内模拟 Intl 类(及其方法),例如:

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

    【讨论】:

    • 感谢您的回答,只是尝试您的建议,但在 beforeAll 中模拟后调用 Intl.DateTimeFormat 时我得到了不确定。 ``` beforeAll(() => { // @ts-ignore _global.Intl = jest.fn(() => { return { DateTimeFormat: () => ({ resolvedOptions: () => ({ timeZone: ' Africa/Nirobi' }), }), }; }); console.log('Intl', Intl.DateTimeFormat); }); ```
    【解决方案2】:

    对于遇到同样问题的任何人,我最终都是这样做的:

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

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2017-03-19
      • 2019-11-22
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2022-06-29
      • 1970-01-01
      相关资源
      最近更新 更多