javascript - QUnit测试ajax成功函数

标签 javascript jquery unit-testing qunit

我知道已经有很多帖子介绍了这一点,但我在基线时并不擅长 Javascript,而且大多数应该有意义的帖子都使用了让我感到困惑的旧语法。

这是我想要工作的功能:

function getUpdateForm() {
  $.ajax({
    url: 'test_response.html',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
      $("#Form_div").html(data);
    },
  });
};

这是我的响应文件:

<html>
  <head>
    <title>Test Response</title>
  </head>
  <body>
    <h1>Test Page</h1>
  </body>
</html>

这是我的 QUnit 测试:

QUnit.test('getUpdateForm ajax request', function(assert) {

  $.ajax = function(request) {
    assert.equal(
      request.url,
      'test_response.html',
      'request url is correct'
    );
    assert.equal(request.type, 'GET',
      'request type is correct'
    );
    assert.equal(request.dataType, 'json',
      'request dataType is correct'
    );
  };

  getUpdateForm();

  setTimeout(function() {
    assert.equal($("#Form_div").html(), '',// not exactly sure what to put
      'Received correct html in response'
    );
    assert.async();
  }, 1000);
});

目前它甚至不尝试在 setTimeout 函数中运行 assert.equal

请尽可能提供详细信息,我可能会有很多问题。第一个问题是,测试如何从 $.ajax = function(request) 获得正确的函数?

最佳答案

我明白你想做什么...但是有一个 tool to mock out Ajax requests为了这个目的! (我是它的维护者,但仍然......)

基本上,在您的测试(或 beforeEach hook )中,您根据真实的 Ajax 调用创建一个模拟,然后进行代码测试。

首先,我将首先在您的源代码函数中添加一个回调,以便我们知道在测试中何时完成 ajax 调用:

function getUpdateForm(doneFunction) {
  $.ajax({
    url: 'test_response.html',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
      $("#Form_div").html(data);
    },
    complete: doneFunction   // <-- this is new!
  });
};

现在使用模拟设置您的测试,并执行断言...

QUnit.test('getUpdateForm ajax request', function(assert) {
  let done = assert.async(); // set up an async test

  $.mockjax({
    url: "test_response.html",
    responseText: "<h1>Test Page</h1>"
  });

  getUpdateForm(function() {  // this is our callback function
    // now do your assertions on the content in the form div...
    assert.equal($("#Form_div h1").text(), 'Test Page', 'Received correct title in html response');

    done(); // then tell QUnit you are done testing.
  });
});

除了 QUnit JS 文件之外,不要忘记包含 Mockjax JS 文件!

关于javascript - QUnit测试ajax成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53974271/

相关文章:

javascript - 在 Backbone.View 中获取模板的计算 CSS 属性

javascript - 回调不是函数错误登录和注册系统

javascript - 根据隐藏的数字更改容器的宽度 - jQuery

javascript - 重新加载浏览器后如何保留在选定的切换按钮/页面中

reactjs - 如何测试 React ErrorBoundary

javascript - 使用子 slug ng-repeat 获取父项的值

jquery - 获取属于包含事件类的div的表单的id

unit-testing - 有人有使用 SQLite 编写集成测试的经验吗?

java - 正确定义 jUnit 测试用例

javascript - javascript/jquery 数组解析