2013-05-15 25 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属性。 –