2017-01-06 115 views
0

我需要測試是否曾發生過window.location.href = data.redirect_path。我怎麼會在Sinon中嘲笑這一點,而不把它從我的試飛員那裏轉移出去?我使用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

您可以如下圖所示stub$ajax。這需要對代碼進行一些重構,以便輕鬆進行測試。

你的成功回調需要是這樣的,

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); 
     }    
     } 
    } 

請參考doc如何location.assign工作。

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 
}); 

我知道,它長超時工作,所以當它失敗你要等待它,但這是一個更好的權衡對我來說比沒有測試證明我的插件行爲與預期相同。

注意jsdom有一個二傳手的window.location最初但sinon可以讓你創建一個。

相關問題