简体   繁体   中英

Qunit ajax async calls with mockajax

I am trying to construct a Qunit test to test an ajax post call. 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:

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

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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