Tamara
Tamara

Reputation: 2980

Mocha + React: navigator is not defined

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?

Upvotes: 5

Views: 9319

Answers (2)

guest
guest

Reputation: 31

... 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"
  };
}

Upvotes: 3

damianfabian
damianfabian

Reputation: 1681

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.

Upvotes: 10

Related Questions