我正在为使用浏览史的组件编写一个测试规格。它引发了一个错误参考:未定义导航器
我尝试了Mocha-chai throws的解决方案" Navigator"未定义。由于React-Router组件,但仍无法正常工作。我可能无法以正确的方式使用解决方案。
这是我的规格文件。
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,
};
您的测试跑步者对应用程序应该运行的环境一无所知,因此window.navigator
/window.location
等不可用。
browserHistory
需要浏览器环境才能正常工作,我认为这是您面临的问题。尝试用createMemoryHistory
替换导入的browserHistory
,看看测试是否通过。
摘录的文档显示了差异:
browserHistory
如果可用时,请使用HTML5历史API,否则又回到了完整的刷新。浏览史需要在服务器端上进行其他配置才能提供URL,但通常是现代网页的首选解决方案。
createMemoryHistory
创建一个内存的历史记录对象,该对象与浏览器URL不相互作用。这对于您需要自定义用于服务器端渲染的历史记录对象,用于自动测试或不想操纵浏览器URL时,例如当您的应用程序嵌入在An。中时,很有用。