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

标签 jquery jasmine mockjax

我有一个基本的 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 stub :

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

同时我尝试编写一个Jasmine描述 block 来测试事件何时触发,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.");
});

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

知道如何重构它以使其正常工作吗?

最佳答案

你猜对了。 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
    });
});

关于jquery - 使用 jquery-mockjax.js stub 进行 Jasmine 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737226/

相关文章:

javascript - jQuery StopPropagation 问题

jquery - 请推荐一个好的JQuery富文本编辑器

javascript - Jasmine 不会从 Assets 管道加载 javascript 文件

javascript - JQuery 可以在预览版中使用,但不能在 Tumblr 上使用

javascript - 如何使用 Jasmine 在 javascript 中模拟新函数/对象创建调用?

angular - 升级到带有 CLI 的 Angular 6 后,测试将不会运行

javascript - mockjax 加载器 - 停止运行特定功能

javascript - qunit + mockjax : When should I call mockjaxClear in async tests?

javascript - Mockjax 可以处理来自 Json 文件的单个 ID Api

jquery - 数据表中的页长度