【问题标题】:I tried to maka a QUnit async test for checking ajax update我试图做一个 QUnit 异步测试来检查 ajax 更新
【发布时间】:2020-06-28 10:06:13
【问题描述】:

我尝试使用 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 的时间不长。

发生错误的部分的sn-p:

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 插件中使用它

【问题讨论】:

    标签: ajax qunit


    【解决方案1】:

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

    【讨论】:

    • 这个解决方案在小提琴中工作。我不知道它是否在 wordpress 中工作(未测试)jsfiddle.net/chLge79y/4
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多