2017-06-22 89 views
3

我的目标是测试我的阵营路由器Route出口在我的应用和测试,如果它加载正确的组件,页面等测试阵营路由器玩笑和酶

我有一个routes.js文件看起来如:

import React from 'react'; 
import { Route, IndexRoute } from 'react-router'; 
import { App, Home, Create } from 'pages'; 

export default (
    <Route path="/" component="isAuthenticated(App)"> 
    <IndexRoute component={Home} /> 
    <Route path="create" component={Create} /> 
    {/* ... */} 
    </Route> 
); 

注:isAuthenticated(App)在别处定义,并略去。

而且从我读过,并理解,我可以测试它是这样:

import React from 'react'; 
import { shallow } from 'enzyme'; 
import { Route } from 'react-router'; 
import { App, Home } from 'pages'; 
import Routes from './routes'; 

describe('Routes',() => { 
    it('resolves the index route correctly',() => { 
    const wrapper = shallow(Routes); 
    const pathMap = wrapper.find(Route).reduce((pathMapp, route) => { 
     const routeProps = route.props(); 
     pathMapp[routeProps.path] = routeProps.component; 
     return pathMapp; 
    }, {}); 
    expect(pathMap['/']).toBe(Home); 
    }); 
}); 

然而,在运行这个测试结果:

Invariant Violation: <Route> elements are for router configuration only and should not be rendered 

我想我明白了问题可能是我使用Enzyme的shallow方法。我从this SO question采取了这个解决方案。我相信我明白它试图通过wrapper来解析调用Route调用,将每个调入一个哈希表并使用它来确定正确的组件是否在表中它应该是,但这是行不通的。

我已经浏览了很多文档,Q & A和博客文章试图找到“正确的方式”来测试我的路线,但我不觉得我在任何地方。我在我的方法基础?

阵营:15.4.2

阵营路由器:3.0.2

酶:2.7.1

节点:6.11.0

回答

3

不能直接呈现Routes,但一个使用内部路由的组件Router。你指出的答案有完整的解决方案。

您可能还需要将测试环境下的browserHistory更改为使用不同的history,该节点适用于节点。旧v3文档: https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md

作为一个方面说明,什么是测试点Route,我认为已经在库本身进行了测试?也许你的测试应该关注你的路由组件:它们是否根据路由参数呈现他们应该做的?这些参数你可以很容易地在你的测试中嘲笑,因为它们只是道具。

我告诉你这一点,因为在我的经验理解什么测试是作为学习如何测试一样重要。希望它有助于:)