0

I'm experiencing an error when I am unit testing:

console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
  Error: Uncaught [Error: Invariant failed: You should not use <Redirect> outside a <Router>]

I know that this is due to the component I am testing having an un-wrapped <Redirect> element:

return <Redirect to={`${myRedirUrl}`}/>;

however this is being returned as part of a fully-fledged and wrapped <ConnectedRouter> so there is no issue with the app actually working. This complaint is merely during unit testing.

Is there anyway in which I can suppress this message during testing? The unit test is passing as I have been checking during trial runs, it's just annoying that the result is being buried...


Component.jsx

export const MyComp = () => {
  // /my-url will cause redirect to RedirectComponent
  return <Redirect to="/my-url" />
}

Test

it('should redirect without error', () => {
  const rendered = render(
      <Provider store={store(state)}>
          <BrowserRouter>
              <MyComponent />
              <Route path='/my-url'>Redirected</Route>
           </BrowserRouter>
       </Provider>
  );

  expect(rendered.container.textContent).toBe('Redirected');
});

This test passes as I have told it to expect the mock component, however I am getting the error as above due to the MyComp not having a wrapped <Redirect>

physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • It's unclear what you're actually testing, but it's pretty easy to render the component in a `MemoryRouter` for a test, or do as I show in https://stackoverflow.com/a/65275037/3001761 and provide a history for testing purposes. See e.g. https://reactrouter.com/web/guides/testing. – jonrsharpe Feb 15 '21 at 15:04
  • @jonrsharpe I've updated my question with a bit more detail about the component/test. Looking at your solution, it didn't do anything to help suppress any errors. – physicsboy Feb 15 '21 at 15:25

0 Answers0