2016-11-23 52 views
1

我正在为使用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, 
}; 
+0

请粘贴的内容。 – biphobe

+0

@bipobe我已添加component.jsx。 – duwalanise

回答

0

你的测试运行不知道你的应用程序应该在运行环境中任何事物,所以window.navigator/window.location等不可用。

browserHistory您正在使用要求浏览器环境正常工作,我认为这是您面临的问题。尝试用createMemoryHistory替换导入的browserHistory并查看测试是否通过。从docs这说明差异


摘录:

browserHistory使用HTML5历史API可用时,将回退到否则完全刷新。 browserHistory需要服务器端的额外配置才能提供URL,但它是现代网页的首选解决方案。

createMemoryHistory创建不与浏览器URL交互的内存中历史记录对象。当你需要定制用于服务器端渲染历史记录对象,进行自动测试,或当你不想操纵浏览器的URL,当应用程序被嵌入在诸如这是有用的。

+0

如上所述,createMemoryHIstory不处理浏览器URL,因此我们无法将browserHistory更改为组件中的createMemoryHistory。作为组分的主要目的是,以反映URL每一个动作,这样我们就可以共享的应用程序的当前状态,以通过URL的任何其他用户。 – duwalanise

+0

@duwalanise我只要求您替换它以查看测试是否通过。无论如何,建议不要将“createMemoryHistory”用于浏览器。你检查了吗? – biphobe

+0

我试过了。它仍然会抛出同样的错误。 – duwalanise