如何测试异步回调

How do I test an asynchronous callback?

本文关键字:异步 回调 测试 何测试      更新时间:2023-09-26

我正在测试一个异步回调,方法是检查它是否在m秒内被调用了n次。

到目前为止,这是我的代码:

test("async callback", function() {
    expect(1);
    var called = 0;
    var callback = function() {called++;};
    var model = new Model(callback);
    model.startCallbacks();
    function theTest() {         // call this a few seconds later and verify
        model.stopCallbacks();   //   that the callback has been called n times
        equal(3, called, "number of times callback was called");
    }
    setTimeout(theTest, 10000); // wait about 10 seconds until calling theTest
});

model.startCallbacksmodel.stopCallbacks是用setInterval实现的。)

这行不通。我认为这是因为当callback仍在异步执行时,执行在测试函数结束时停止。

我要测试的内容:model正在正确调用callback。我该怎么做?

// use asyncTest instead of test
asyncTest("async callback", function() {
    expect(1);
    var called = 0;
    var callback = function() {called++;};
    var model = new Model(callback);
    model.startCallbacks();
    function theTest() {         // call this a few seconds later and verify
        model.stopCallbacks();   // that the callback has been called
        equal(3, called, "number of times callback was called");
        // THIS IS KEY: it "restarts" the test runner, saying
        // "OK I'm done waiting on async stuff, continue running tests"
        start();
    }
    setTimeout(theTest, 10000); // wait about 10 seconds until calling theTest
});

您应该使用异步测试的启动和停止函数(请参阅文档),例如:

test("a test", function() {
  stop();
  $.getJSON("/someurl", function(result) {
    equal(result.value, "someExpectedValue");
    start();
  });
});

你的例子是:

test("async callback", function() {
    stop(1);
    var called = 0;
    var callback = function() {called++;};
    var model = new Model(callback);
    model.startCallbacks();
    function theTest() {         // call this a few seconds later and verify
        model.stopCallbacks();   //   that the callback has been called n times
        equal(3, called, "number of times callback was called");
        start();
    }
    setTimeout(theTest, 10000); // wait about 10 seconds until calling theTest
});

您也可以使用快捷方式asyncTest。