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


application code calling location.href = "some-url". want write test verify navigation redirect has happened.

using jest on jsdom, tried overriding location.href setter using jest mock function , working.

but can't seems restore location.href property @ test cleanup, , failing rest of tests 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   });    someappcodethatshouldredirecttosomeurl();    expect(spyfn).tobecalledwith('http://some-url'); // working    // cleanup code, not working, because originallocationhref undefined   object.defineproperty(window.location, 'href', originallocationhref);   }); 

what missing? why object.getownpropertydescriptor(window.location, 'href'); undefined?

is there better way intercept navigation events in order test it?

thanks

use location.assign() method instead instead of assigning new location string location.href. can mock , test no problems:

it('test navigation happened', () => {   window.location.assign = jest.fn();    // here call location.assign('http://some-url');   someappcodethatshouldredirecttosomeurl();    expect(window.location.assign).tobecalledwith('http://some-url');    // location.href hasn't changed because location.assign mocked }); 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -