javascript - 如何使用 Sinon/Qunit 模拟 'timeout' 或 'failure' 响应?

标签 javascript unit-testing jquery qunit sinon

我在模拟成功条件时没有遇到任何问题,但似乎无法理解在使用 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 调用处理程序听到失败或超时方法?我唯一想尝试的是:

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

但它不起作用。

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

最佳答案

对于超时,sinon的fake timers有帮助。使用它们你不需要将超时设置为 1ms。至于失败,你的做法looks correct大部头书。你能给我们更多的代码,尤其是故障处理程序吗?

关于javascript - 如何使用 Sinon/Qunit 模拟 'timeout' 或 'failure' 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560475/

相关文章:

javascript - Js函数总是返回相同的值

jquery - 如何调整 jquery DatePicker 弹出窗口的位置以避免 iFrame 剪切

javascript - Angular js - 解析和运行()的执行顺序

python - `py.test` 和 `__init__.py` 文件

JavaScript 数组问题

c# - VS 11 单元测试框架

.net - 有没有更好的方法来为具有很多字段的对象实现 Equals?

jquery - 如何使用jquery按特定文本选择按钮

javascript - 使用imacros eval通过正则表达式提取值

javascript - 如何在一定的时间间隔内重新执行一个函数?