I have a simple 404 component that will change the window.location to prepend "/404" to the current location.
const My404 = () => {
const location = useLocation();
useEffect(() => {
window.location.replace(`/404${location.pathname}`);
}, []);
...
I am attempting to test this with React Testing Library but I can't seem to get it to see the change, even after using await waitFor...
it('Should add /404 to start of pathname', async () => {
const history = createMemoryHistory()
history.push('/some-route')
const rendered = render(
<Router history={history}>
<My404 />
</Router>
);
await waitFor(() => expect(window.location.pathname).toBe('/404/some-route'));
});
The test fails:
Expected: "/404/some-route"
Received: "/"
UPDATE
I just did a quick check by logging out both the location and the window.location.pathname before and after the change...
location:
{ location:
{
pathname: '/some-route',
search: '',
hash: '',
key: '14xswz'
}
}
window.location.pathname:
/
I managed to solve the issue before @Chris gave me the suggestion to use the React-specific
useHistoryhook instead. I will outline both ways in which I fixed the test.Not using useHistory - The old-fashioned way
Using useHistory I reworked the component to use the
useHistoryhook rather than relying onwindow.location.I then updated the test to reflect the changes