ajaxqunit

I tried to maka a QUnit async test for checking ajax update


I tried to maka a QUnit async test for checking ajax update.

I read of QUnit.asyncTest here https://www.sitepoint.com/test-asynchronous-code-qunit/ but if i try this i get a TypeError: QUnit.asyncTest is not a function thats the complete source: https://gist.github.com/232457b002e5363439aece7535600356

of course i new by using QUnit and used JavaScript not for long time.

that a snippet of the part where the error happens:

function max() {
   var max = -Infinity;
   for (var i = 0; i < arguments.length; i++) {
      if (arguments[i] > max) {
         max = arguments[i];
      }
   }

   return max;
}
//   https://www.sitepoint.com/test-asynchronous-code-qunit/
//TypeError: QUnit.asyncTest is not a function
QUnit.asyncTest('max', function (assert) {
   expect(1);

   window.setTimeout(function() {
      assert.strictEqual(max(3, 1, 2), 3, 'All positive numbers');
      QUnit.start();
   }, 0); 
});

this test gives no syntax error but gives old date:

QUnit.test('usersInnerHTMLlength_Is24', function(assert) {
// problem: this not reads the updates done by ajax. means that are old data:
    let innerHTMLlength = $("#users").html().toString().length;
    assert.equal(innerHTMLlength, 24);
});

May its not possible to check ajax with QUnit? I thougt this when i have read here: QUnit testing AJAX calls

I use it inside a Wordpress Plugin


Solution

  • That sitepoint article is very old (by web standards). You'll need to use the newer syntax found on the documentation website:

    function someAsyncThing(value) {
      return new Promise(function (resolve, reject) {
        setTimeout(function() {
          if (value > 5) {
            resolve(value);
          } else {
            reject(new Error("bad value"));
          }
        }, 500);
      });
    }
    
    
    QUnit.test( "some async thing success test", function( assert ) {
      // This is what tells QUnit the test is asynchronous
      // "done" here will be a callback function used later
      var done = assert.async();
      
      // Now call your Async code, passing in a callback...
      someAsyncThing(10)
        .then(function(result) {
          // do your assertions once the async function ends...
          assert.equal(result, 10)
          
          // Now tell QUnit you're all done with the test
          done();
        })
        // we can pass the "done" callback from above into catch() to force a test failure
        .catch(done);
    });
    
    QUnit.test( "some async thing FAILURE test", function( assert ) {
      var done = assert.async();
      someAsyncThing(4)
        .then(function() {
          done(new Error("we should NOT succeed with a value < 5"));
        })
        .catch(function(err) {
          assert.equal(err.message, "bad value")
        });
    });