How does one mock global.navigator.userAgent
for use inside Jest?
Let’s get to it!
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'])
)
Reference the setup file in the Jest configuration. Below highlights, the standalone configuration file type.
setupFiles: ["<rootDir>/ROUTE_TO_SETUP_FILE"],
Start leveraging your mocking abilities!
test('simple test', () => {
global.navigator.userAgent = 'bond james bond'
expect(global.navigator.userAgent).toBe('bond james bond')
})