2012-03-01 96 views
1

我试图通过检查它的调用,例如n时间m秒来测试ansync回调。如何测试异步回调?

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

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.stopCallbackssetInterval实现)。

这是行不通的。我认为这是因为执行测试功能结束,而callback仍然是异步执行。

我想测试的是:model正确调用callback。我该怎么做呢?

+0

我只需要RTFM。多么尴尬。 – 2012-03-01 20:52:59

回答

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

您应该使用的启动和停止功能的异步测试(见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