How to mock window.navigator.language using jest

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

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(() => {
    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});

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

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

43 thoughts on “How to mock window.navigator.language using jest”