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

查看:121
本文介绍了如何使用 jest 模拟 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', configure: 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')
})
...

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

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