我正在为使用browserHistory的组件编写测试规范。它会抛出一个错误 ReferenceError:导航器没有定义测试React-router组件抛出导航器未定义
我试过从Mocha-Chai throws "navigator not defined" due to React-router component解决方案,但它仍然无法正常工作。可能是我无法正确使用解决方案。
这是我的spec文件。
import React from 'react';
import { expect } from 'chai';
import jsdom from 'jsdom';
import sinon from 'sinon';
import shallow from 'enzyme';
import { MyComponent } from 'component.jsx';
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.document = doc;
global.window = doc.defaultView;
global.navigator = {
userAgent: 'node.js',
};
describe('<Component />',() => {
let wrapper;
before(() => {
sinon.stub(Component.prototype, 'componentWillMount');
wrapper = shallow(<Component />);
});
context('Component',() => {
it('should render component',() => {
expect(wrapper.type()).to.equal('div');
});
});
after(() => {
Component.prototype.componentWillMount.restore();
});
});
任何帮助将不胜感激。谢谢。
这里是component.jsx文件
import React, { Component, PropTypes } from 'react';
import R from 'ramda';
import { browserHistory } from 'react-router';
export class MyComponent extends Component {
componentWillMount() {
const query = this.props.location.query;
// looping through the query object of url
R.mapObjIndexed((value, key) => this.prepareStateData(value, key), query);
}
componentDidUpdate(prevProps) {
// this push the url every time the component is updated
if (this.props.urlHistory && this.props.urlHistory !== prevProps.urlHistory) {
browserHistory.push(this.props.urlHistory);
}
}
prepareStateData(value, key) {
// this changes the state according to the url
switch (key) {
case 'query1': {
// do something
break;
}
case 'query2': {
// do something
break;
}
default:
// do something
break;
}
}
render() {
return (
<div>
{ /* render part */ }
</div>
);
}
}
MyComponent.propTypes = {
location: PropTypes.object,
urlHistory: PropTypes.string,
};
请粘贴 的内容。 –
biphobe
@bipobe我已添加component.jsx。 – duwalanise