How to test <Redirect> from `react-router` with RTL (React Test Library) and JEST
Let’s suppose we have the following code
const Task = ({ data }) => {
if (data.state === 'closed') return <Redirect to='/tasks' />
return <Task />
}
If task is closed then we have to be redirected to a task list. How to test this code? There is no obvious way described in react-router. Let me show you a way. It’s not a perfect way, but it may help you.
A component which uses <Redirect> must be placed in a <Router> wrapper from react-router. For our test we will use a fake Router which was created specially for testing purposes.
Our fake router will have only 2 routes.
First one will render the root path with a tested component.
Second one will render just a RedirectUrl.
If our component redirects to a required path then we can to check it via just simple string matching.
Let’s create a testing helper with the test router.
Let’s use our testing router for a test.
If <Task />component redirects to a right URL then the test will pass.
That is it.
Do you know a better way? Please share it in comments. Thank you!
Happy testing!