DEV Community

Alan Garcia
Alan Garcia

Posted on

Answer: Intercept navigation change with jest.js (or how to override and restore location.href)

Use location.assign() method instead instead of assigning new location string to location.href. Then you can mock and test it with no problems:

it('test navigation happened', () => {
  window.location.assign = jest.fn();

  // here you call location.assign('http://some-url');
  redirectToSomeUrl();

  expect(window.location.assign).toBeCalledWith('http://some-url');

  // location.href hasn't changed because location.assign was mocked
});

Top comments (0)