samedi 14 juillet 2018

Javascript test for window.location.assign not working

I am trying to test code that redirects to an external url. A manual test shows that the redirect happens, but the test doesn't recognize that 'window.location.assign' has been called. The code looks like this:

function redirectUser(foo) {
  if (foo.active) {
    window.location.assign("http://newUrl.com");
  }

And here's the test:

it('redirects to newUrl when active', () => {
  redirectUser({"active": true});
  const mock = jest.fn(window.location.assign);
  expect(mock).toBeCalled();
});

When I run it, however, the test fails with this message:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

I've tried adding another toy function just above window.location.assign and tested that, and it does get called, test passes. Does window.location need some special treatment? What am I doing wrong here?

(This's my first SO question. :) )

Aucun commentaire:

Enregistrer un commentaire