测试返回按钮在React Router v6中的行为



我有一个react应用程序,使用react路由器和react测试库进行测试。我正在从react路由器v5.1升级到v6。

我有一个测试,验证了当浏览器返回按钮被点击时发生的事情(一个模式被驳回)。在旧版本的测试中,我使用了history包中的createMemoryRouter来模拟后退按钮的按下,如下所示:

const history = createMemoryHistory();
render(
<Router history={history}>
<Route path="/">
<App />
</Route>
</Router>
);
// perform some setup
history.goBack();
// make assertions about state of application

,但由于v6使用钩子与历史交互,因此不可能像这样传递历史对象。那么,如何测试应用程序与后退按钮的交互呢?

您可以创建一个自定义的MemoryRouter,允许您传入自己的history对象。为了重构的目的,使用源MemoryRouter。

MemoryRouter

export function MemoryRouter({
basename,
children,
initialEntries,
initialIndex,
}: MemoryRouterProps): React.ReactElement {
let historyRef = React.useRef<MemoryHistory>();
if (historyRef.current == null) {
historyRef.current = createMemoryHistory({ initialEntries, initialIndex });
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location,
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}

注意MemoryRouter维护自己的内部history引用。这就是我们想要"曝光"的内容。

创建一个新的自定义路由器,使用historyprop代替。

const CustomRouter = ({ history, ...props }) => {
const [state, setState] = React.useState({
action: history.action,
location: history.location,
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
{...props}
location={state.location}
navigationType={state.action}
navigator={history}
/>
};

从这里导入CustomRouter,并传递给它一个实例化的内存history对象。

的例子:

import { createMemoryHistory } from 'history';
import Router from '../path/to/CustomRouter';
const history = createMemoryHistory();

render(
<Router history={history}>
<Route path="/">
<App />
</Route>
</Router>
);
// perform some setup
history.goBack();
// make assertions about state of application

最新更新