如何使用Sinon/Qunit模拟"超时"或"失败"响应?

Car*_*ine 11 javascript jquery unit-testing qunit sinon

我没有解决模拟成功条件的问题,但似乎无法理解如何在使用Sinon和Qunit测试和ajax函数时模拟失败/超时条件:

我的设置如下:

$(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();
        }
    });
Run Code Online (Sandbox Code Playgroud)

和我的成功案例测试,愉快地运行并接收/通过接收的数据到成功方法是这样的:

    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();
    });
Run Code Online (Sandbox Code Playgroud)

但是,我无法解决我应该做的事情而不是这个:

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

让我的ajax调用处理程序'听到'失败或超时方法?我唯一能想到的就是:

        xhr.requests[0].respond(408);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我做错了什么或者我误解了什么?所有帮助非常感谢:)

Adr*_*ine 1

对于超时,sinon\xe2\x80\x99s假定时器可以提供帮助。使用它们,您\xe2\x80\x99不需要将超时设置为 1 毫秒。至于失败,我认为你的方法是正确的。你能给我们更多的代码,特别是失败处理程序吗?

\n