【问题标题】:How to write unit test to embeded ajax requests?如何编写单元测试来嵌入 ajax 请求?
【发布时间】:2013-08-15 18:11:15
【问题描述】:

我有启动文件下载的 handleDownload 方法。该函数发布到后端,后端返回响应,基于新请求发布到文件所在的服务器。我看到我可以使用mockjax 来模拟请求,但是如何处理成功、错误等不同的路径。我应该如何知道哪个响应触发了哪个路径(成功、错误、完成……)。什么是测试 handleDownload 函数的好方法,以及如何测试?对于嘲笑,我使用Sinon.js 我还没有真正深入的了解。我还应该检查是否调用了 handleDownloadFinal 函数。

handleDownload: function(data, url) {
$.ajax({
    type: "POST",
    url: url,
    data: {},
    success: function(response) {
        if (response.success) {
            var start_token = response.token;
            $.ajax({
                type: start_token.method,
                url: start_token.url,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Authorization', start_token.header);
                },
                success: function(start_response) {
                    handleDownloadFinal(start_response.status_token);
                },
                error: function(start_response) {
                    $.ajax({
                        type: "POST",
                        url: url + 'proxy/',
                        success: function(fallback_response) {
                            if (fallback_response.success) {
                                handleDownloadFinal(fallback_response.status_token, true, fallback_response.job_uuid);
                            } else {
                                errorDownload(response.error);
                            }
                        },
                        error: function(fallback_response) {
                            // Now this is some real error                                    
                            generalErrorDownload();
                        },
                        dataType: 'json'
                    });
                },
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                }
            });
        } else {
            errorDownload(response.error);
        }
    },
    error: function(response) {
        generalErrorDownload();
    },
    complete: function() {
    },
    dataType: "json"
});

}

【问题讨论】:

    标签: qunit sinon mockjax


    【解决方案1】:

    你应该使用 sinon 自带的fake server

    before(function(){
        //create the server 
        this.server = sinon.fakeServer.create();
        // let the server automatically respond for every request
        server.autoRespond = true;
    })
    
    it('test something', function(){
    
        //let the server respond for  specific url with 200-ok
        this.server.respondWith("POST", "/some/article/comments.json", [200, {
          "Content-Type": "application/json"
        }, '[{ "id": 12, "comment": "Hey there" }]']);
    })
    

    由于您有一堆请求并且您必须检查所有组合,我建议为每个请求失败成功设置帮助函数,以便您可以像这样测试案例:

    function letFirstRequestSucceed() {
      this.server.respondWith("POST", "urlForFirstRequest", [200, {
        "Content-Type": "application/json"
      }, '[{ "id": 12, "comment": "Hey there" }]']);
    }
    
    
    function letSecondRequestFail() {
      this.server.respondWith("POST", "urlForSecondRequest", [404, {
        "Content-Type": "application/json"
      }, '{error: "some error message"}');
    }
    
    
    function letThirdRequestFail() {
      this.server.respondWith("POST", "urlForThirdRequest", [404, {
        "Content-Type": "application/json"
      }, '{error: "some error message"}');
    }
    
    it("should to something when the second and third request fails", function () {
      sinon.spy(window, 'generalErrorDownload');
      letFirstRequestSucceed();
      letSecondRequestFail();
      letThirdRequestFail();
    
      handleDownload('someDate', 'aUrl');
    
      expect(generalErrorDownload)
    
    })
    

    顺便说一句,您应该考虑使用 api ajax 调用支持的 jquerys deferred 重构您的代码,这将使您的代码更具可读性。

    【讨论】:

    • 当我模拟出来并使用 fakeServer 时,事情会同步运行,对吧?
    • 是的,假服务器会立即调用成功/错误消息。
    • 您必须调用server.respond() 告诉服务器从AJAX 请求返回,通常是在执行测试断言之前。你可以用server.autoRespond = true开启同步模式,虽然我没试过。
    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2017-02-15
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    相关资源
    最近更新 更多