您可以将路由器包装在一个组件中以对其进行测试。
路由.jsx
export default props => (
<Router history={browserHistory}>
...
<Route path="nurse/authorization" component{NurseAuthorization}/>
...
</Route>
)
索引.js
import Routes from './Routes.jsx';
...
ReactDOM.render(<Routes />, document.getElementById('root'));
然后你必须对你的Routes
组件进行浅渲染,你可以创建一个对象映射来检查路径和相关组件之间的对应关系。
路由测试.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);
});
编辑
如果您想额外处理渲染props的情况:
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 />}/>