使用jquery-mockjax.js存根进行Jasmine测试



我有一个基本的jQuery ajax调用,我使用jQuery .mockjax.js模拟响应:

$(document).ready(function() {        
    $("button.ajax").on("click", getAjaxResult);
});
function getAjaxResult() {
    $.getJSON("/restful/get", function(response) {
      if ( response.status == "success") {
        $("p.ajax_result").html( response.result );
      } else {
        $("p.ajax_result").html( "There is a problem, cannot ajax get." );
      }
    });
}

jquery.mockjax.js存根:

$.mockjax({
  url: "/restful/get",
  responseText: {
    status: "success",
    result: "Your ajax was successful."
  }
});

在同一时间,我试图写一个茉莉花描述块测试当事件被触发,ajax以及结果是成功的:

it("ajax result should be shown after the button is clicked", function() {
    spyEvent = spyOnEvent("button.ajax", "click");
    $("button.ajax").trigger("click");
    expect("click").toHaveBeenTriggeredOn("button.ajax");
    expect(spyEvent).toHaveBeenTriggered();
    getAjaxResult();
    expect($("p.ajax_result")).toHaveText("Your ajax was successful.");
});

当我运行测试时,它总是失败。我怀疑在ajax完成之前执行了expect() ?

你知道我怎么重构它使它工作吗?

你猜对了。mockjax插件保留ajax调用的异步特性,因此您的expect()在ajax调用完成之前触发。您需要更改getAjaxResult()函数以使用回调,以便知道它在测试中何时完成:

function getAjaxResult(cb) {
    $.getJSON("/restful/get", function(response) {
      if ( response.status == "success") {
        $("p.ajax_result").html( response.result );
      } else {
        $("p.ajax_result").html( "There is a problem, cannot ajax get." );
      }
      cb(response);
    });
}

那么你的测试是这样的…

it("ajax result should ...", function(done) {  // <<< Note the `done` arg!
    spyEvent = spyOnEvent("button.ajax", "click");
    $("button.ajax").trigger("click");
    expect("click").toHaveBeenTriggeredOn("button.ajax");
    expect(spyEvent).toHaveBeenTriggered();
    getAjaxResult(function() {  // <<< Added the callback here
        expect($("p.ajax_result")).toHaveText("Your ajax was successful.");
        done();  // <<< Don't forget to tell jasmine you're done
    });
});

最新更新