0

I'm testing if my components render with Redux successfully with React Testing Library. I'm having trouble having my utility component to pass the renderWithRedux test. This is my App component.

function App() {
return (
    <>
        <Router>
            <NavBar />
            <div className="container">
                <Switch>
                    <Route exact path='/' component={Home}/>
                    <AuthRoute exact path='/login' component={Login} />
                    <AuthRoute exact path='/signup' component={Signup} />
                    <Route exact path='/users/:handle' component={UserProfile} />
                    <Route exact path='/users/:handle/post/:postId' component={UserProfile} />
                </Switch>
            </div>
        </Router>
    </>
);

}

Here is my AuthRoute utility component.

const AuthRoute = ({ component: Component, authenticated, ...rest }) => (
      // if authenticated, redirect to homepage, otherwise redirect to signup or login
        <Route
        {...rest}
        render={(props) =>
          authenticated === true ? <Redirect to='/' /> : <Component {...props} />
        }
      />
    );

AuthRoute.test.js

const renderWithRedux = () => render(
    <Provider store={myStore}>
        <AuthRoute />
    </Provider>
);

it('renders with Redux', () => {
    const {} = renderWithRedux(<AuthRoute />);
});

I've attempted the solutions from Invariant failed: You should not use <Route> outside a <Router>, but to no avail. I appreciate any help, thank you.

ln09nv2
  • 207
  • 1
  • 17

2 Answers2

5

Render the component under test into a router

import { MemoryRouter } from 'react-router-dom';

const renderWithRedux = ({ children }) => render(
    <Provider store={myStore}>
        {children}
    </Provider>
);

it('renders with Redux', () => {
    const {} = renderWithRedux(
      <MemoryRouter>
        <AuthRoute />
      </MemoryRouter>
    );
});
Drew Reese
  • 43,833
  • 5
  • 21
  • 43
  • Thanks, but I received `Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.` – ln09nv2 Aug 20 '20 at 22:29
  • @kennjamin in your `renderWithRedux` did you really intend to wrap whatever component was passed to it in a test (*i.e. render the children passed to it*)? I updated my answer. – Drew Reese Aug 20 '20 at 22:50
  • It worked! You're right, I should had changed wrapping the `App` component to instead wrap with children. Thank you! – ln09nv2 Aug 20 '20 at 23:08
0

Just like the Provider to wrap redux things you have to wrap your components with routes using MemoryRouter for the tests.

import { MemoryRouter } from 'react-router';

  • Thanks, but I received `Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.` – ln09nv2 Aug 20 '20 at 22:29