Как шпионить / заглушки с мокко / чай на ajax .fail () и .done ()? - PullRequest
0 голосов
/ 10 января 2019

Я новичок в модульном тестировании мокко / чай. У меня есть следующий вызов 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 голосов
/ 11 января 2019

Вам необходимо встроить тестовый вызов 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)) 
});
...