1

I use useNavigate from react-router-dom to handle navigation. I called a useNavigate hook at the top level of the functional component like that: const navigate = useNavigate(). Inside a handleClick() function I use it to navigate to an another page of my website like that: navigate("/home"). I tried it and it is working fine, if I click on the button it takes me to homepage (http://localhost/home). However I have problems unit testing this functionality. After simulating a click on that button, the url should change so I wrote the following expectation: expect(global.window.location.href).toContain('/home');

The test fails, the window location did not change. However when I tried to console log the window location in the afterEach() method, it shows that after the test the global.window.location.href equals to http://localhost/home. So it is working just can`t verify that in my test....

Why it is only change after the test? What can I do to verify that url inside the test?

ptjr
  • 11
  • 2
  • Did you try using `waitFor`? – Konrad Aug 26 '22 at 19:18
  • Yes, did not work. I also tried using async-await, that solved the problem but VSCODE returned a message " 'await' has no effect on the type of this expression." I don't really understand how can it help if it should have no effect, so still looking for a better solution. – ptjr Aug 27 '22 at 11:38
  • Please show entire test code – Konrad Aug 27 '22 at 14:44

0 Answers0