2017-01-06 4 views
0

window.location.href = data.redirect_pathが起きたかどうかをテストする必要があります。テストランナーから私をリダイレクトせずに、私はシノンでどのようにこれを嘲笑しますか?私はchai/mocha.jsを私のテストランナーとしてティースプーンと共に使用しています。mocha/chaiを使用したAJAXリクエスト内のwindow.location.hrefのユニットテスト

$.ajax({ 
    type: 'PUT', 
    url: $url, 
    dataType: 'json', 
    data: { user: $userData }, 
    success: function(data) { 
     if (data.success == true) { 
     window.location.href = data.redirect_path 
     } else { 
     $errorsContainer.html(data.html); 
     $codeInput.select(); 
     if (typeof data.redirect_path !== 'undefined') { 
      window.location.href = data.redirect_path 
     }    
     } 
    } 
    }); 

答えて

0

あなたはajaxため$stub、以下に示すことができますよう。これは簡単にテストできるように、コードにリファクタリングが必要です。

あなたの成功コールバックは

success: function(data) { 
     if (data.success == true) { 
     window.location.assign(data.redirect_path) 
     } else { 
     $errorsContainer.html(data.html); 
     $codeInput.select(); 
     if (typeof data.redirect_path !== 'undefined') { 
      window.location.assign(data.redirect_path); 
     }    
     } 
    } 

location.assignが動作しているかdocを参照してください、このようにする必要があります。

it("should fake successful ajax request", function() { 
    sinon.stub($, "ajax").yieldsTo("success", {redirect_path: '/home', success: true}); 
    sinon.stub(window.location, 'assign'); // stubbing the assign. so that it wont redirect to the given url. 

    //here you call the function which invokes $.ajax(); 
    someFunction(); 

    // assert here 

    // manually restoring the stubs. 
    $.ajax.restore(); 
    window.location.assign.restore(); 
}) 
1

私は同じような問題で最後の2〜3時間、私の髪を引き出しています。残念ながら、window.location = hrefを使用して移動することは、プラグインで非常に重要な動作でしたので、私はそれを信念に取ることができませんでした。上記を使用してwindow.location.assign(href)私のために働いていない - おそらくjsdomのため、わからない。

最後に私の場合は(かなり)単純な解決策を考え出しました。

it('reloads the page when using the browsers back button', (done) => { 
    let stub = sinon.stub(window, 'location').set(() => { done() }); 

    // do whatever you need to here to trigger 
    // window.location = href in your application 
}); 

は、私はそれは長いタイムアウト上で動作していることを知っているので、それが失敗したとき、あなたはそれを待つようになってきましたが、それは予想通り、私のプラグインの動作を証明なしのテストを持っていないよりも、私にとってははるかに優れたトレードオフです。

NOTE jsdomないはもともとwindow.location用セッターを持っているが、sinonは、あなたがものを作成することができます。

関連する問題