【发布时间】:2021-08-06 21:20:57
【问题描述】:
我有一个对 url 搜索更改做出反应的组件,以及一个更改 url 搜索的按钮。我想测试当我单击按钮时,组件会做出相应的反应。这是一个代码框:https://codesandbox.io/s/react-testing-library-url-change-test-b5zq1。
App.js
export default function App() {
const [urlChanged, setUrlChanged] = useState(false);
const handleURLSearchChange = () => {
window.location.search = new URLSearchParams({ foo: "bar" });
};
useEffect(() => {
if (window.location.search.length !== 0) {
setUrlChanged(true);
}
}, []);
return (
<div>
<button aria-label="change" onClick={handleURLSearchChange}>
Change URL search
</button>
<p aria-label="URL Status">{urlChanged ? "Changed!" : "Not yet"}</p>
</div>
);
}
App.spec.js
describe("App", () => {
it("Reacts to url changes when touching the button", async () => {
render(<App />);
const button = await screen.findByLabelText("change");
userEvent.click(button);
const label = await screen.findByLabelText("URL Status");
await waitFor(() => expect(label).toHaveTextContent("Changed!"));
});
});
问题是我得到了:
Error: Not implemented: navigation (except hash changes)
注意:我只有在下载沙箱并运行 npm install 和 npm test 时才能看到此错误。
我是否必须同时使用 setter 和 getter 来模拟 window.location 对象?有什么更好的方法?
【问题讨论】:
-
JSDOM 不支持导航:github.com/jsdom/jsdom/issues/2112。您要么需要用测试替身替换
window.location,要么使用类似 React Router 的东西(请参阅 reactrouter.com/web/guides/testing 了解如何测试)。
标签: reactjs jestjs mocking react-testing-library jsdom