2012-03-01 95 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