我试着做一个 QUnit 异步测试来检查 ajax 更新

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

我试着做一个 QUnit 异步测试来检查 ajax 更新。

我在这里读到 QUnit.asyncTest https://www.sitepoint.com/test-asynchronous-code-qunit/ 但如果我尝试这个,我会得到一个 TypeError: QUnit.asyncTest is not a function 这就是完整的来源:https://gist.github.com/232457b002e5363439aece7535600356

当然,我是通过使用 QUnit 新来的,并且使用 JavaScript 时间不长。

发生错误的部分片段:

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); 
});

此测试未给出语法错误,但给出了旧日期:

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);
});

可能无法使用 QUnit 检查 ajax? 当我在这里阅读时,我想到了这一点: QUnit testing AJAX calls

我在 Wordpress 插件中使用它

那篇 sitepoint 文章 非常 旧(按照网络标准)。您需要使用 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")
    });
});