Halestorm Dev

Jest Mock UserAgent

By David Hale on Dec 21, 2019

How does one mock global.navigator.userAgent for use inside Jest?
Let’s get to it!

Create configuration method

Create a setup file or append this method to an existing setup file:

Object.defineProperty(
  window.navigator,
  'userAgent',
  ((value) => ({
    get() {
      return value
    },
    set(v) {
      value = v
    },
  }))(window.navigator['userAgent'])
)

Setup into Jest

Reference the setup file in the Jest configuration. Below highlights, the standalone configuration file type.

  setupFiles: ["<rootDir>/ROUTE_TO_SETUP_FILE"],

Profit

Start leveraging your mocking abilities!

test('simple test', () => {
  global.navigator.userAgent = 'bond james bond'
  expect(global.navigator.userAgent).toBe('bond james bond')
})