2013-05-15 45 views
9

我已經沒有問題,整理出嘲諷的成功條件,但似乎無法捉摸如何使用興農和Qunit測試和Ajax功能時嘲笑失敗/超時條件:如何使用Sinon/Qunit模擬「超時」或「失敗」響應?

我的設立是這樣的:

$(document).ready(function() { 

    module("myTests", { 
     setup: function() { 
      xhr = sinon.sandbox.useFakeXMLHttpRequest(); 
      xhr.requests = []; 
      xhr.onCreate = function (request) { 
       xhr.requests.push(request); 
      }; 

      myObj = new MyObj("#elemSelector"); 
     }, 
     teardown: function() { 
      myObj.destroy(); 
      xhr.restore(); 
     } 
    }); 

和我的成功案例測試,開心地運行和接收/通過接收到的數據傳遞到成功的方法是這樣的:

test("The data fetch method reacts correctly to receiving data", function() { 
     sinon.spy(MyObject.prototype, "ajaxSuccess"); 

     MyObject.prototype.fetchData(); 

     //check a call got heard 
     equal(1, xhr.requests.length); 

     //return a success method for that obj 
     xhr.requests[0].respond(200, { "Content-Type": "application/json" }, 
       '[{ "responseData": "some test data" }]'); 

     //check the correct success method was called 
     ok(MyObj.prototype.ajaxSuccess.calledOnce); 

     MyObj.prototype.ajaxSuccess.restore(); 
    }); 

不過,我不知道是什麼我應該代替推杆這個:

 xhr.requests[0].respond(200, { "Content-Type": "application/json" }, 
       '[{ "responseData": "some test data" }]'); 

使我的ajax調用處理程序「聽到」一個失敗或超時的方法?我唯一能想到的就是這樣:

 xhr.requests[0].respond(408); 

但它不起作用。

我在做什麼錯,或者我誤解了什麼?所有幫助非常感謝:)

+0

超時是在給定時間內缺乏響應,所以你不能返回超時 –

+0

我希望sinon可能會克服,併爲所有類型的響應提供標準化的接口。如果我不能使用sinon'返回'超時 - 那麼我該如何僞造一個呢? –

+0

我不知道sinon所以也許有一些特定的,但通常你設置超時說1ms,並使用服務器或模擬服務器端的等待。 –

回答

0

對於超時,sinon的fake timers可能會有所幫助。使用它們,您不需要將超時設置爲1ms。至於失敗,你的方法looks correct給我。你能給我們更多的代碼,特別是失敗處理程序嗎?

0

做這樣的事情

requests[0].respond(
     404, 
     { 
      'Content-Type': 'text/plain', 
      'Content-Length': 14 
     }, 
     'File not found' 
); 

工程引發的jQuery AJAX請求 '錯誤' 回調。

至於timouts,您可以使用sinons假時鐘這樣的:

test('timeout-test', function() { 
    var clock = sinon.useFakeTimers(); 
    var errorCallback = sinon.spy(); 

    jQuery.ajax({ 
     url: '/foobar.php', 
     data: 'some data', 
     error: errorCallback, 
     timeout: 20000 // 20 seconds 
    }); 

    // Advance 19 seconds in time 
    clock.tick(19000); 

    strictEqual(errorCallback.callCount, 0, 'error callback was not called before timeout'); 

    // Advance another 2 seconds in time 
    clock.tick(2000); 

    strictEqual(errorCallback.callCount, 1, 'error callback was called once after timeout'); 
}); 
+1

也許是去jQuery的Ajax的方式,但CJ詢問sinon的假XHR;這些方法都不適用於Sinon。 –

-1

設置超時您$.ajax()通話,並使用興農fake timers來響應之前向前移動時鐘。

+0

CJ沒有進行$ .ajax()調用,而是一個sinon虛假的XHR調用,並且sinon不支持.timeout屬性。 –