Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
Tamara Avatar asked Dec 15 '22 01:12

Tamara


2 Answers

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.

like image 57
damianfabian Avatar answered Dec 17 '22 00:12

damianfabian


... 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"
  };
}
like image 45
guest Avatar answered Dec 17 '22 01:12

guest