2017-09-12 112 views
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

有沒有更好的方法來攔截導航事件以便測試它?

感謝

回答

4

使用location.assign()方法來代替,而不是分配新的位置字符串location.href。那麼你可以模擬和測試沒有問題:

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

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

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

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