React 测试库不变性失败:您不应在 <Router> 之外使用 <Route>

ln0*_*nv2 2 reactjs redux react-testing-library

我正在使用 React 测试库测试我的组件是否成功地使用 Redux 呈现。我的实用程序组件无法通过 renderWithRedux 测试。这是我的 App 组件。

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>
    </>
);
Run Code Online (Sandbox Code Playgroud)

}

这是我的 AuthRoute 实用程序组件。

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} />
        }
      />
    );
Run Code Online (Sandbox Code Playgroud)

AuthRoute.test.js

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

it('renders with Redux', () => {
    const {} = renderWithRedux(<AuthRoute />);
});
Run Code Online (Sandbox Code Playgroud)

我尝试了Invariant的解决方案失败了:你不应该在 <Router> 之外使用 <Route>,但无济于事。我感谢任何帮助,谢谢。

Dre*_*ese 6

将被测组件渲染到路由器中

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

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

it('renders with Redux', () => {
    const {} = renderWithRedux(
      <MemoryRouter>
        <AuthRoute />
      </MemoryRouter>
    );
});
Run Code Online (Sandbox Code Playgroud)