gpt4 book ai didi

reactjs - Jest 测试 React Router Prompt

转载 作者:行者123 更新时间:2023-12-05 03:05:03 24 4
gpt4 key购买 nike

我有一个包含 React Router 的组件 <prompt>在其中,现在我想 Jest 测试当用户离开组件并且满足所需的先决条件时是否显示它。我如何模拟这种导航并查看是否在 Jest 中触发了“提示”?

最佳答案

也许有人需要针对这种情况的解决方案:

import React from "react";
import { render } from "@testing-library/react";
import { Prompt, Route, Router, Switch, useHistory } from "react-router-dom";
import { PromptProps } from "react-router";
import { createMemoryHistory } from "history";

const promptResult = jest.fn(); // jest function which holds "when" value of prompt

jest.mock("react-router-dom", () => {
const PromptMock: React.FC<PromptProps> = (props: PromptProps) => {
const history = useHistory();
if (props.when) {
history.block(); //simulation of prompt behavior
}
promptResult.mockReturnValue(props.when);
return <div />;
};

const originalModule = jest.requireActual("react-router-dom");
return {
__esModule: true,
...originalModule,
Prompt: PromptMock,
};
});

test("Shows prompt on navigation away", () => {
const history = createMemoryHistory({ initialEntries: ["/path1"] });

render(
<Router history={history}>
<Switch>
<Route path="/path1">
<div>
<Prompt when={true} message={"You have unsaved changes."} />
<div>Should prevent user from navigation</div>
</div>
</Route>
<Route path="/path2">
<div>Some other page</div>
</Route>
</Switch>
</Router>
);

history.push("path2");

expect(promptResult()).toBeTruthy();
});

test("Doesn't show prompt on navigation away", () => {
const history = createMemoryHistory({ initialEntries: ["/path2"] });

render(
<Router history={history}>
<Switch>
<Route path="/path1">
<div>
<Prompt when={true} message={"You have unsaved changes."} />
<div>Should prevent user from navigation</div>
</div>
</Route>
<Route path="/path2">
<div>Some other page</div>
</Route>
</Switch>
</Router>
);

history.push("path2");

expect(promptResult()).toBeFalsy();
});

关于reactjs - Jest 测试 React Router Prompt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51415975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com