Mocking globals in Jest

The correct way of doing this is to use spyOn. The other answers here, even though they work, don't consider cleanup and pollute the global scope.

// beforeAll
jest
  .spyOn(window, 'navigator', 'get')
  .mockImplementation(() => { ... })

// afterAll
jest.restoreAllMocks();

As every test suite run its own environment, you can mock globals by just overwriting them. All global variables can be accessed by the global namespace:

global.navigator = {
  onLine: true
}

The overwrite has only effects in your current test and will not effect others. This also a good way to handle Math.random or Date.now.

Note, that through some changes in jsdom it could be possible that you have to mock globals like this:

Object.defineProperty(globalObject, key, { value, writable: true });