I have a component which reacts to url search changes, and a button that changes the url search. I want to test that when I click the button, the component reacts accordingly. Here's a codesandbox: 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!"));
});
});
The problem is I'm getting:
Error: Not implemented: navigation (except hash changes)
Note: I'm only able to see this error if I donwload the sandbox, and run npm install and npm test.
Do I have to mock the window.location object with both setters and getters? What's the better way to do it?