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

Application code is calling location.href = "some-url". I want to write a test that verify the navigation redirect has happened.

Using jest on jsdom, I tried to do it with overriding location.href setter using jest mock function and it is working.

But now I can't seems to restore the location.href property at the test cleanup, and it failing the rest of the tests which relay on 'location.href'.

it('test navigation happened', () => {
  const originalLocationHref = Object.getOwnPropertyDescriptor(window.location, 'href'); // returns undefined

  spyFn = jest.fn();
  Object.defineProperty(window.location, 'href', {
    set: spyFn,
    enumerable: true,
    configurable: true


  expect(spyFn).toBeCalledWith('http://some-url'); // this is working

  // Cleanup code, not working, because originalLocationHref is undefined
  Object.defineProperty(window.location, 'href', originalLocationHref);  

What am I missing? Why Object.getOwnPropertyDescriptor(window.location, 'href'); is undefined?

Is there a better way to intercept navigation events in order to test it?



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');


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

Need Your Help

Matplotlib markers disappear when edgecolor = 'none'

python matplotlib python-2.7 markers

I'm trying to make a scatter plot of some PCA data. I do some pretty typical code:

Jackson JSON library: how to instantiate a class that contains abstract fields

java json jackson deserialization

I want to convert a JSON string into java object, but the class of this object contains abstract fields, which Jackson can't instantiate, and doesn't produce the object. What is the easiest way to ...