Nic*_*nek 9 mocha.js chai react-router
我正在为使用react-router的React组件编写测试.我正在使用Mocha和Chai以及Chai-jQuery.
我的测试工作正常,直到我将一个组件从react-router导入一个组件(例如Link).此时,我收到以下错误:
ReferenceError: navigator is not defined
at Object.supportsHistory (/Users/nico/google-drive/code/agathos/client/node_modules/history/lib/DOMUtils.js:61:12)
Run Code Online (Sandbox Code Playgroud)
我曾经在react-bootstrap上遇到类似的错误,直到我更新到react-bootstrap v0.29.3.我有最新版本的react-router v2.4.0(和历史v2.1.1).但问题仍然存在.
我发现的唯一解决方案是改变node_modules/history/lib/DOMUtils: navigator进入window.navigator.这是一个黑客,而不是一个好的解决方案.
我认为问题出在react-router上,但我没有解决方案.
以防万一,这是我的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};
Run Code Online (Sandbox Code Playgroud)
Jon*_*ang 30
似乎react-router假设navigator是在全球范围内.
要解决此错误,您应该navigator在测试设置阶段添加到全局范围:
global.navigator = {
userAgent: 'node.js'
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5686 次 |
| 最近记录: |