简体   繁体   English

QUnit Ajax与Mockajax异步调用

[英]Qunit ajax async calls with mockajax

I am trying to construct a Qunit test to test an ajax post call. 我正在尝试构造一个Qunit测试来测试ajax调用。 I am using mockajax to mock the call. 我正在使用嘲笑模拟呼叫。 However, I can't get the test to work with the asynchronous call. 但是,我无法使测试与异步调用一起使用。

Here is my source code: 这是我的源代码:

source.js: source.js:

ajaxFunc  = function(element){
  $.post({
  type:'POST',
  url: '/temp/',
  dataType:'json',
  success: function(data){
    element.text("changed in func");
  },
  error: function(data){
    //do something
  },
  timeout: 60000
      });
}

syncFun = function(element){
  element.text("changed in func");
}

Here is my test code: 这是我的测试代码:

tests2.js tests2.js

function mockSuccess(){
  $.mockjax({
    url: "/temp/",
    responseText:  { success: true }
  });
}

QUnit.test( "test ajax async", function( assert ) {
  mockSuccess();
  var done = assert.async();
  var element = document.createElement("div");
  ajaxFunc($(element));
  $(element).text("old");
  setTimeout(function() {
    assert.strictEqual($(element).text(), 'changed in func');
    done();
  });
});

QUnit.test( "test sync", function( assert ) {
  var element = document.createElement("div");
  $(element).text("old");
  syncFun($(element));
  assert.strictEqual($(element).text(), 'changed in func');
});

The first tests fails, and the second one succeeds. 第一个测试失败,第二个成功。 If I put a comment in the source.js within the success callback, I see in fact that the the post succeeds and changes the elements text. 如果我在成功回调中的source.js中添加注释,则实际上我看到帖子成功了,并更改了元素文本。

In other words, everything works correctly except testing the results of the post. 换句话说,除了测试帖子的结果之外,其他所有内容都可以正常工作。

I have looked at https://qunitjs.com/cookbook/ and the examples on stack overflow with no luck. 我看过https://qunitjs.com/cookbook/ ,但是没有运气的情况下堆栈溢出的示例。

It looks like I just need to add a number of milliseconds to get the async call to work: 看来我只需要增加几毫秒就可以使异步调用正常工作:

QUnit.test( "test ajax async", function( assert ) {
  mockSuccess();
  var done = assert.async();
  var element = document.createElement("div");
  ajaxFunc($(element));
  $(element).text("old");
  setTimeout(function() {
   assert.strictEqual($(element).text(), 'changed in func');
   done();
  }, 800);
  // ^^^
});

I have seen examples like this in the github for qunit, so I guess this is correct, but I can see problems where you don't set the time function high enough. 我在github上的qunit上看到了这样的例子,所以我想这是正确的,但是我会看到一些问题,其中您没有将时间函数设置得足够高。

I have already moved all of the processing that occurs in success: and error: outside the post function, so I can test it independently of the ajax calls, but I still wanted to test the actual post for various types of errors. 我已经将成功进行的所有处理:和错误:都移到了post函数之外,因此我可以独立于ajax调用对其进行测试,但是我仍然想测试实际的post是否存在各种类型的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM