我正在使用 enzyme + Mocha + Chai 来测试我的react-redux项目。 enzyme 提供浅层来测试组件行为。但我没有找到测试路由器的方法。我正在使用 react 路由器,如下所示:
<Router history={browserHistory}>
...
<Route path="nurse/authorization" component{NurseAuthorization}/>
...
</Route>
我想测试此路由 nurse/authorization
引用 NurseAuthorization
组件。如何在reactjs项目中测试它?
编辑1
我使用react-router
作为路由器框架。
最佳答案
您可以将路由器包装在组件内以对其进行测试。
Routes.jsx
export default props => (
<Router history={browserHistory}>
...
<Route path="nurse/authorization" component{NurseAuthorization}/>
...
</Route>
)
index.js
import Routes from './Routes.jsx';
...
ReactDOM.render(<Routes />, document.getElementById('root'));
然后你必须浅渲染你的 Routes
组件,并且你可以创建一个对象映射来检查路径和相关组件之间的对应关系。
Routes.test.js
import { shallow } from 'enzyme';
import { Route } from 'react-router';
import Routes from './Routes.jsx';
import NurseAuthorization from './NurseAuthorization.jsx';
it('renders correct routes', () => {
const wrapper = shallow(<Routes />);
const pathMap = wrapper.find(Route).reduce((pathMap, route) => {
const routeProps = route.props();
pathMap[routeProps.path] = routeProps.component;
return pathMap;
}, {});
// { 'nurse/authorization' : NurseAuthorization, ... }
expect(pathMap['nurse/authorization']).toBe(NurseAuthorization);
});
编辑
如果您想另外处理渲染 Prop 的情况:
const pathMap = wrapper.find(Route).reduce((pathMap, route) => {
const routeProps = route.props();
if (routeProps.component) {
pathMap[routeProps.path] = routeProps.component;
} else if (routeProps.render) {
pathMap[routeProps.path] = routeProps.render({}).type;
}
return pathMap;
}, {});
只有在直接渲染要测试的组件(没有额外的包装器)的情况下它才会起作用。
<Route path="nurse/authorization" render{() => <NurseAuthorization />}/>
关于reactjs - 如何用 enzyme 测试 react 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41531465/