Skip to content
Advertisement

TypeError: Cannot read property ‘navigator’ of undefined

My unit test case started failing when I started running the unit test in mocha from karma, Earlier we were using karma and –browser to run the test case but it was running fine,

JavaScript

Package.json

JavaScript

test file –

It fails for navigator here, TypeError: Cannot read property ‘navigator’ of undefined

JavaScript

ReferenceError: navigator is not defined

JavaScript

Advertisement

Answer

Accessing global.window.navigator is an error both in a browser (where global is not defined) and in Node.js (where there is no global window object, and also no navigator).

If that test were to run in a browser, you could just redefine the userAgent on navigator (or equivalently window.navigator), i.e.

JavaScript

But if you run that test in Node.js without a DOM emulation setup you will run into an error because navigator is undefined. You could mock navigator of course before mocking userAgent, but then for your test to pass you would also need to mock navigator.mediaDevices and navigator.mediaDevices.enumerateDevices, and in the end you would test nothing but the mock code itself.

Conclusion: use DOM emulation (JSDom, cheerio) or run your test in a real browser with Karma or Puppeteer.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement