如何测试异步回调?

时间:2012-03-01 20:38:30

标签: javascript asynchronous qunit

我正在尝试通过检查它在n秒内被调用m次来测试异步回调。

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

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。我该怎么做?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

您应该使用start和stop函数进行异步测试(参见docs),例如:

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