如何在ajax .fail()和.done()上使用mocha / chai进行间谍/存根?

时间:2019-01-10 20:11:52

标签: javascript ajax unit-testing mocha sinon

我是摩卡/柴单元测试的新手。我有以下ajax呼叫正在进行服务呼叫。我已经将.fail().done()添加为ajax调用的一部分。

所以我不确定我在这里缺少什么。抱歉,如果我在这里缺少基本的东西。有人可以在这里描述出什么问题吗?

function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
    $.ajax({
        type: method,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: endPointurl,
        headers: search_headers,
        xhrFields: {
            withCredentials: true
        },
        success: function success(results, xhr, XMLHttpRequest) {
            successCallback();
        },
        error: function (xhr, textStatus, error) {
           callErrorFunc();
        }
    }).fail(function (xhr, textStatus, errorThrown) {
       callFailFunc();
    }).done(function () {
        callDoneFunction();
    });
}

我写了以下单元测试:

describe.only('Testing searchdoctorAPIcall function', function () {
    var testurl = 'https://abc.serve.org/getData';
    beforeEach(function() {
        sinon.stub($, 'ajax');
    });

    afterEach(function() {
        $.ajax.restore();
    });

    it('should make an ajax call', function(done) {
        searchAPIcall(testurl, "GET", {"Content-Type":"application-json;charset=utf-8",X-Id":"1da9b0c8-bb52"}, "baseSearch");
        expect($.ajax.calledOnce).to.be.true; 
        done(); 
    });
});

在执行单元测试时,总是出现以下错误。

undefined is not an object (near '...} }).fail(function (xhr,...')

但是当我更改searchAPIcall函数并删除.dail()和.done()单元测试通过时。

function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
    $.ajax({
        type: method,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: endPointurl,
        headers: search_headers,
        xhrFields: {
            withCredentials: true
        },
        success: function success(results, xhr, XMLHttpRequest) {
            successCallback();
        },
        error: function (xhr, textStatus, error) {
           callErrorFunc();
        }
    })
}

现在,如果我运行单元测试,那么它将通过。

should make an ajax call (passed)

1 个答案:

答案 0 :(得分:0)

您需要将测试done调用编入代码,以便在异步调用和测试完成后运行它:

function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
    return $.ajax({ // return the call so it can be chained
        ...
    });
}

it('should make an ajax call', function(done) {
    searchAPIcall(
      testurl,
      "GET",
      {"Content-Type":"application-json;charset=utf-8","X-Id":"1da9b0c8-bb52"}, // Note: you are missing a " before the 'X' in this line
      "baseSearch"
    ).done(() => {
      expect($.ajax.calledOnce).to.be.true;
      done();
    }).fail(done); // Equivalent to: .fail(error => done(error)) 
});