Mocha + React: navigator is not defined

江枫思渺然 提交于 2019-12-08 02:09:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41194264/mocha-react-navigator-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!