1
應用程序代碼調用location.href = "some-url"
。 我想編寫一個驗證導航重定向發生的測試。攔截導航改變jest.js(或如何覆蓋和恢復location.href)
在jsdom上使用jest,我試着用重寫的location.href setter使用jest mock函數來實現它,它工作正常。
但現在我似乎無法在測試清理中恢復location.href屬性,並且它失敗了繼續在'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
?
有沒有更好的方法來攔截導航事件以便測試它?
感謝