如何使用玩笑来模拟window.navigator.language [英] How to mock window.navigator.language using jest

查看:67
本文介绍了如何使用玩笑来模拟window.navigator.language的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在玩笑的单元测试中模拟浏览器中的window.navigator.language属性,以便可以测试页面上的内容使用的是正确的语言

I am trying to mock the window.navigator.language attribute in the browser in my jest unit tests so I can test that the content on my page is using the correct language

我发现有人在网上使用此功能

I have found people online using this:

Object.defineProperty(window.navigator, 'language', {value: 'es', configurable: true});

我已经将其设置在测试文件的顶部,并且可以在其中运行

I have set it right at the top of my test file and it is working there

但是,当我在单个测试中重新定义(并且人们设置为确保可配置性设置为true)时,它不会重新定义它并且仅使用旧值,有人知道肯定要更改它的方法吗?

however, when I redefine in an individual test (and people set to make sure configurable was set to true) it wont redefine it and is just using the old value, does anyone know a way to definitely change it?

beforeEach(() => {
    jest.clearAllMocks()
    Object.defineProperty(global.navigator, 'language', {value: 'es', configurable: true});
    wrapper = shallow(<Component {...props} />)
})

  it('should do thing 1', () => {
      Object.defineProperty(window.navigator, 'language', {value: 'de', configurable: true});
      expect(wrapper.state('currentLanguage')).toEqual('de')
    })

it('should do thing 2', () => {
  Object.defineProperty(window.navigator, 'language', {value: 'pt', configurable: true});
  expect(wrapper.state('currentLanguage')).toEqual('pt')
})

对于这些测试,它不会将语言更改为我设置的新语言,而是始终使用顶部的语言.

for these tests it is not changing the language to the new language I have set, always using the one at the top

推荐答案

window.navigator及其属性是只读的,这就是为什么需要Object.defineProperty来设置window.navigator.language的原因.应该可以多次更改属性值.

window.navigator and its properties are read-only, this is the reason why Object.defineProperty is needed to set window.navigator.language. It's supposed to work for changing property value multiple times.

问题在于该组件已经在beforeEach中实例化,window.navigator.language的更改不会影响它.

The problem is that the component is already instantiated in beforeEach, window.navigator.language changes don't affect it.

使用Object.defineProperty手动模拟属性将需要存储原始描述符并也手动对其进行恢复.这可以通过jest.spyOn完成. jest.clearAllMocks()对于手动间谍/嘲弄无济于事,对于Jest间谍来说可能不需要.

Using Object.defineProperty for mocking properties manually will require to store original descriptor and restore it manually as well. This can be done with jest.spyOn. jest.clearAllMocks() wouldn't help for manual spies/mocks, it may be unneeded for Jest spies.

可能应该是:

let languageGetter;

beforeEach(() => {
  languageGetter = jest.spyOn(window.navigator, 'language', 'get')
})

it('should do thing 1', () => {
  languageGetter.mockReturnValue('de')
  wrapper = shallow(<Component {...props} />)
  expect(wrapper.state('currentLanguage')).toEqual('de')
})
...

这篇关于如何使用玩笑来模拟window.navigator.language的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆