使用jest.js拦截导航更改(或如何覆盖和恢复location.href) [英] Intercept navigation change with jest.js (or how to override and restore location.href)
问题描述
应用程序代码正在调用 location.href =some-url
。
我想写一个测试来验证导航重定向是否已经发生。
Application code is calling location.href = "some-url"
.
I want to write a test that verify the navigation redirect has happened.
在jsdom上使用jest,我尝试使用覆盖location.href setter来完成它jest模拟函数,它正在工作。
Using jest on jsdom, I tried to do it with overriding location.href setter using jest mock function and it is working.
但是现在我似乎无法在测试清理时恢复location.href属性,并且它在其余的测试中失败了哪个接收'location.href'。
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
});
someAppCodeThatShouldRedirectToSomeUrl();
expect(spyFn).toBeCalledWith('http://some-url'); // this is working
// Cleanup code, not working, because originalLocationHref is undefined
Object.defineProperty(window.location, 'href', originalLocationHref);
});
我缺少什么?为什么 Object.getOwnPropertyDescriptor(window.location,'href');
是 undefined
?
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?
谢谢
推荐答案
使用 location.assign()方法,而不是将新的位置字符串分配给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
});
这篇关于使用jest.js拦截导航更改(或如何覆盖和恢复location.href)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!