Javascript 在全局级别上模拟函数实现的Jest

Javascript 在全局级别上模拟函数实现的Jest,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我有一个实用函数,看起来像这样: const getTimezoneString = (): string => { return Intl.DateTimeFormat().resolvedOptions().timeZone; }; 由于此功能是在多个新旧浏览器上运行的应用程序的一部分,因此我想测试对不同平台的Intl支持 我正在寻找一种全局定义Intl对象的模拟实现的方法,以便在执行以下操作时: expect(getTimezoneString()).toEquall(&quo

我有一个实用函数,看起来像这样:

const getTimezoneString = (): string => {
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
};
由于此功能是在多个新旧浏览器上运行的应用程序的一部分,因此我想测试对不同平台的
Intl
支持

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

expect(getTimezoneString()).toEquall("Africa/Nirobi")
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')
});
类似地,我将在实现中更改时区,并测试我的函数是否返回新的时区

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

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

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

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

您需要全局模拟
Intl
类(及其方法),比如:

expect(getTimezoneString()).toEquall("Africa/Nirobi")
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')
});

对于遇到同样问题的人,我就是这样做的:

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

谢谢你的回答,只是尝试一下你的建议,但是在beforeAll中模拟了
Intl.DateTimeFormat
之后,我在调用它时没有定义以前(()=>{/@ts ignore{u global.Intl=jest.fn(()=>{return{DateTimeFormat:()=>({resolvedOptions:()=>({timeZone:'Africa/Nirobi'}),}),};});console.log('Intl',Intl.DateTimeFormat:());})```