问题
I have my react-router component such as :
<Switch>
<Route
path="/abc"
render={() => <ComponentTemplateABC component={containerABC} />}
/>
<Route
path="/def"
render={() => <ComponentTemplateDEF component={containerDEF} />}
/>
...
...
</Switch>
I wish to test the routing to ensure the respective component is rendered for each route. However, I do not wish to use mount for testing the routing, only wish to use shallow rendering.
Below is what my test looks like currently:
test('abc path should route to containerABC component', () => {
const wrapper = shallow(
<Provider store={store}>
<MemoryRouter initialEntries={['/abc']}>
<Switch>
<AppRouter />
</Switch>
</MemoryRouter>
</Provider>,
);
jestExpect(wrapper.find(containerABC)).toHaveLength(1);
});
This test does not work with shallow, because shallow won't render the full child hierarchy. So I tried an alternate approach:
test('abc path should render correct routes and route to containerABC component', () => {
const wrapper = shallow(<AppRouter />);
const pathMap = wrapper.find(Route).reduce((pathMap, route) => {
const routeProps = route.props();
pathMap[routeProps.path] = routeProps.component;
return pathMap;
}, {});
jestExpect(pathMap['/abc']).toBe(containerABC);
});
This test does not work for me, because I am using render in my routing code instead of Component directly as in below:
<Route path="..." **render**={() => <Component.. component={container..} />}
Hence, I am unable to test my routes. How do I test my routes using shallow rendering or as above or basically, any other approach that does not use mount?
Any help would be much appreciated. Thank you in advance.
回答1:
So far I may suggest you different ways to test that:
- Mocking
ComponentABC
+mount()
import containerABC from '../../containerABC.js';
jest.mock('../../containerABC.js', () => <span id="containerABC" />);
...
const wrapper = mount(
<Provider store={store}>
<MemoryRouter initialEntries={['/abc']}>
<Switch>
<AppRouter />
</Switch>
</MemoryRouter>
</Provider>,
);
jestExpect(wrapper.find(containerABC)).toHaveLength(1);
shallow()
+dive()
+renderProp()
:
const wrapper = shallow(
<Provider store={store}>
<MemoryRouter initialEntries={['/abc']}>
<Switch>
<AppRouter />
</Switch>
</MemoryRouter>
</Provider>,
);
jestExpect(wrapper.find(AppRouter)
.dive()
.find(Route)
.filter({path: '/abc'})
.renderProp('render', { history: mockedHistory})
.find(ContainerABC)
).toHaveLength(1);
来源:https://stackoverflow.com/questions/58887090/testing-react-router-with-shallow-rendering