'How to test that <Navigate /> will navigate app to correct component
I use react-router-dom v6
Routing component.
if (!loaded) {
return <Spiner/>;
}
return <Routes>
<Route
path="/login"
element={
<Public>
<Suspense fallback={...}>
<LoginComponent />
</Suspense>
</Public>
}
/>
<Route
path="/protected"
element={
<Private>
<Suspense fallback={...}>
<Protected />
</Suspense>
</Private>
}
/>
</Routes>
Private wrapper
const Private = ({children}) => {
const {state} = useLocation();
const {loggedIn} = useAuthHook();
if (!loggedIn) {
return <Navigate to="/login" state={state}/>
}
return children;
}
So, what I'm trying to do.
I try to test, that application will navigate to <LoginComponent/> if user is not loggedIn.
test.each([{route: "/protected"}])
("will render login page if user is not loggedIn", async ({route}) => {
const {getByText, history} = render(<RoutingContainer />,
{routeHistory: [route],
preloadedState: preloadedStateWithFalseLoggedIn
})
await waitFor(() => expect(getByText(/Sign in/i)).toBeInTheDocument());
expect(history.location.pathname).toBe("/login");
})
In the terminal we can see that I received empty div.
If I remove line with await waitFor(...) the test will pass.
I guess that thing is with <Navigate />.
How can I test component that will be rendered after use <Navigate/>?
UPDATED
I use Routing component inside RoutingContainer
const RoutingContainer = () => {
const {checkedWho} = useSelector(state => state.login);
useEffect(() => {
dispatch(whoAmIRequest());
}, []);
return (
<Routing loaded={checkedWho}/>
)
}
Solution 1:[1]
I think you forgot screen and put the text in quotes. And I always use a timeout for async assertions.
await waitFor(()=>expect(screen.getByText('Sign in')).toBeInTheDocument(),{timeout: 5000})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MWO |


