【问题标题】:How to mock window.navigator.language in jest 27如何在 jest 27 中模拟 window.navigator.language
【发布时间】:2021-08-20 13:59:55
【问题描述】:

我有一个类似的功能

export function formatDate(date: string){
    return new Intl.DateTimeFormat(navigator.language).format(new Date(date))
}

我正在尝试用 vanilla jest 编写单元测试(不使用 jsdom 库),但正如您所见,我需要能够模拟 window.navigator.language

到目前为止,我已经尝试过了,

test('UK date format', () => {
  Object.defineProperty(window.navigator, 'language', {value: 'en-GB', configurable: true})
  expect(window.navigator.language).toBe('en-GB')
})

但我一生都无法理解您应该如何开玩笑地模拟 window.navigator。

理想情况下,我希望能够在每次测试中为 window.navigator.language 模拟一个新值。所以我可以对en-USfr 等进行测试

任何帮助理解你应该如何模拟这个将不胜感激。

【问题讨论】:

标签: typescript unit-testing jestjs navigator ts-jest


【解决方案1】:

您可以使用 Jest 模拟 window.navigator.language,如下所示:

let windowSpy;

beforeEach(() => {
    // Spy on the read-only window function which
    // returns a reference to the current window.
    windowSpy = jest.spyOn(window, 'window', 'get');
});

// Clean-up the spy after every test
afterEach(() => windowSpy.mockRestore());

const setMockLanguage = (language: string) =>
    // Set how you want window.navigator.language to behave
    windowSpy.mockImplementation(() => ({
        navigator: {
            language
        }
    }));

test('UK date format', () => {
    setMockLanguage('en-GB');

    expect(window.navigator.language).toBe('en-GB');
});

test('US date format', () => {
    setMockLanguage('en-US');

    expect(window.navigator.language).toBe('en-US');
});

我在代码中包含了一些 cmets 来提供帮助。

【讨论】:

  • @ChrisB 好消息 :)
  • 你如何在 TypeScript 中做到这一点?
猜你喜欢
  • 2020-10-02
  • 2021-06-09
  • 2021-11-02
  • 2019-12-26
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2016-11-14
相关资源
最近更新 更多