Mocha-Chai throws “navigator not defined” due to R

2019-04-22 11:04发布

I am writing a test for a React component that uses react-router. I am using Mocha with Chai and Chai-jQuery.

My tests work fine, until I import a component from react-router into a component (e.g. Link). At this point, I get the following error:

ReferenceError: navigator is not defined
    at Object.supportsHistory (/Users/nico/google-drive/code/agathos/client/node_modules/history/lib/DOMUtils.js:61:12)

I used to get a similar error with react-bootstrap until I updated to react-bootstrap v0.29.3. I have the most recent version of react-router v2.4.0 (and history v2.1.1). But the problem persists.

The only solution I have found is to change node_modules/history/lib/DOMUtils: navigator into window.navigator. This is a hack though, and not a good solution.

I think the problem is with react-router, but I don't have a solution.

Just in case, here is my test-helper.js.

import jquery from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './reducers';

// set up a testing environment to run like a browser in the command line
// create a fake browser and html doc
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
// prevent jquery defaulting to the dom by giving it access to the global.window
const $ = jquery(window);

// build renderComponent function that should render a React class
function renderComponent(ComponentClass, props = {}, appState = {}) {
  const componentInstance =  TestUtils.renderIntoDocument(
    <Provider store={createStore(reducers, appState)}>
      <ComponentClass {...props} />
    </Provider>
  );
  // produces html
  return $(ReactDOM.findDOMNode(componentInstance));
}

//build a helper for simulating events
// $.fn allows you to add a custom function to your jquery library
$.fn.simulate = function(eventName, value) {
  if (value) {
    // `this` allows you to access the object appended to
    // `val()` is a jquery function that sets the value of selected html element
    this.val(value);
  }
  // the [] are object method selectors, which allow you to access e.g. Simulate.change
  TestUtils.Simulate[eventName](this[0]);
};

// set up chai jquery
chaiJquery(chai, chai.util, $);

export {renderComponent, expect};

1条回答
老娘就宠你
2楼-- · 2019-04-22 11:29

It seems that react-router assumes navigator is in the global scope.

To resolve this error, you should add navigator to the global scope in your test setup phase:

global.navigator = {
  userAgent: 'node.js'
};
查看更多
登录 后发表回答