24

我在整理模拟成功条件时没有问题,但似乎无法理解在使用SinonQunit测试和 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();
        }
    });
});

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

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 调用处理程序hear成为失败或超时方法?我唯一能想到尝试的是:

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

但它不起作用。

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

4

3 回答 3

0

For the timeout, sinon’s fake timers could help. Using them you wouldn’t need to set the timeout to 1ms. As for the failures, your approach looks correct to me. Can you give us more code, especially the failure handler?

于 2013-05-30T08:59:13.277 回答
0

做这样的事情

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

用于触发 jQuery AJAX 请求中的“错误”回调。

至于超时,您可以像这样使用 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');
});
于 2014-02-07T13:12:26.067 回答
-1

在你的$.ajax()调用上设置一个超时,并在响应之前使用 Sinon假计时器来提前移动时钟。

于 2014-02-25T16:54:47.500 回答