【发布时间】:2021-04-10 14:12:25
【问题描述】:
我正在尝试在我的 React 应用程序中测试私有路由。我正在使用以下版本:
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "^4.0.3",
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
在我的 PrivateRoute.js 中,我只是检查用户是否已登录并进行相应的重定向:
...
const PrivateRoute = (props) => {
const { component: Component, ...rest } = props;
const user = useContext(AuthContext);
return (
<Route
{...rest}
render={(matchProps) =>
user ? <Component {...matchProps} /> : <Redirect to="/SignIn" />
}
/>
);
};
...
在我的 PrivateRoute.test.js 中,我只是渲染<PrivateRoute> 并检查history.location.pathname。但是,当我期待/SignIn 时,我总是得到/。
describe("<PrivateRoute/>", () => {
it("redirects unauthenticated users to SignIn", async () => {
const history = createBrowserHistory();
render(
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/SomeRoute" component={SomeComponent} />
</Switch>
</BrowserRouter>
);
expect(history.location.pathname).toBe("/SignIn");
});
});
我错过了什么?
【问题讨论】:
标签: javascript reactjs react-router react-testing-library