2017-09-12 5 views
1

アプリケーションコードはlocation.href = "some-url"です。 ナビゲーションリダイレクトが行われたことを確認するテストを作成したいと思います。jest.jsによるナビゲーションの変更のインターセプト(またはlocation.hrefのオーバーライドおよび復元方法)

jsdomでjestを使用して、jest mock関数を使用してlocation.hrefセッターをオーバーライドしようとしましたが、動作しています。

しかし、私はテストクリーンアップで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 
}); 
関連する問題