【发布时间】:2018-12-27 04:44:40
【问题描述】:
我有一个组件,其中包含一个 React Router <prompt>,现在我想测试当用户离开该组件并且满足所需的先决条件时是否显示该组件。如何模拟此导航并查看是否在 Jest 中触发了“提示”?
【问题讨论】:
标签: reactjs react-router jestjs react-router-v4
我有一个组件,其中包含一个 React Router <prompt>,现在我想测试当用户离开该组件并且满足所需的先决条件时是否显示该组件。如何模拟此导航并查看是否在 Jest 中触发了“提示”?
【问题讨论】:
标签: reactjs react-router jestjs react-router-v4
也许有人需要这个案例的解决方案:
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();
});
【讨论】:
我不确定 Jest 是否是测试这个的正确工具。您通常会将它用于单元测试和测试是否按预期工作应该超出单元测试的范围。你想做的事情听起来更像是一个集成测试。
【讨论】: