Mocha + React: navigator is not defined

9.1k views Asked by At

I'm trying to write the first test for React components and keep getting error:

ReferenceError: navigator is not defined

I have component and one of it's children use codemirror for displaying editable textareas. The thing is that in codemirror there is a check for type of navigator. And since I run this code not in browser, but in terminal with node.js it's not defined.

Some folks on SO advised to set global variable, but it didn't work for me. Here is code of the test:

global.navigator = {
    userAgent: 'node.js'
};

import React from 'react'
import { shallow, render } from 'enzyme'
import { expect } from 'chai'
import { MessagesView } from '../../components/MessagesView'

describe('components', () => {
    describe('Message views', () => {
        it('render buttons', () => {

        })
    })
})

Is there still a way to set navigator variable? Or maybe I can set global variables with mocha options?

2

There are 2 answers

0
damianfabian On BEST ANSWER

Take a look here https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md

Basically you need to configure jsdom to create the window object for you.

var jsdom = require('jsdom').jsdom;

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    global[property] = document.defaultView[property];
  }
});

global.navigator = {
  userAgent: 'node.js'
};

This should be placed in the setup file of Mocha.

0
guest On

... this did change a littlebit.

2021 approach


const JSDOM = require( "jsdom" ).JSDOM;

/**
 *  Simulate browser environment for nodejs.
 */
module.exports.browserenv =  function() {
  const cfg       = { url: "http://localhost" };
  const dom       = new JSDOM( "", cfg );
  global.window   = dom.window;
  global.document = dom.window.document;

  Object.keys( global.window ).forEach(( property ) => {
    if ( typeof global[ property ] === "undefined" ) {
         global[ property ] = global.window[ property ];
    }
  });

  global.Element   = window.Element;
  global.Image     = window.Image;
  // maybe more of: global.Whatever = window.Whatever

  global.navigator = {
    userAgent: "node.js"
  };
}