【发布时间】:2017-11-26 05:58:57
【问题描述】:
我的目标是在我的应用程序中测试我的 React Router 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 调用,将每个调用放入一个哈希表中并使用它来确定正确的组件是否在它应该在的表中,但这是不工作。
我查看了很多文档、问答和博客文章,试图找到“正确的方法”来测试我的路线,但我觉得我没有取得任何进展。我的方法是否离谱?
反应:15.4.2
反应路由器:3.0.2
酶:2.7.1
节点:6.11.0
【问题讨论】:
标签: node.js reactjs react-router jestjs enzyme