如何使用玩笑来模拟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')
})
...