2016-04-25 66 views
0

在下面的代碼中,兩個函數在異步模塊的幫助下同時運行。一旦得到兩個函數的結果,就調用最終函數dosomething3()。我將如何測試是否調用了適當的回調函數?如何測試異步模塊中是否按預期調用回調?

async.parallel([ 
    function(cb) { 
     doSomething1(function(err, result) { 
      if (err) return cb(err); // WANT TO TEST 
      cb(null, result); //WANT TO TEST 
     }); 
    }, 

    function(cb) { 
     doSomething2(function(err, result) { 
      if (err) return cb(err); // WANT TO TEST 
      cb(null, result); //WANT TO TEST 
     }); 
    } 

], function(err, data) { 
    if (err) return handleError(err); //WANT TO TEST 
    var result1 = data[0]; 
    var result2 = data[1]; 

    dosomething3(result1, result2, function(err) { 
     if (err) return handleError(err); 
     process.exit(0); 
    }) 
}); 
+0

如何使用的console.log'如果(ERR){的console.log( 'doSomething1錯誤',ERR);返回cb(err); }'等等,在每個回調中 – Molda

+0

是的,請使用console.log或使用管理斷點的IDE運行代碼。 –

+0

你想調試回調函數還是確保所有的回調函數都沒有錯誤? –

回答

0

如果你想要編寫單元測試,你必須爲函數doSomething1,了doSomething2,dosomething3,嘲笑的HandleError。因此,根據測試用例,您可以設置(或不設置)來自這些函數的錯誤。

例如,模擬了doSomething1()看起來像這樣(它只是想法,興農提供了工具來測試功能,通話時看到here):

// global variables that are used to controll data passed in callback of doSomething1() 
var doSomething1Error = null, 
    doSomething1result = [], 
    doSomething1CallCount = 0; 
// the mock 
function doSomething1(cb) { 
    doSomething1CallCount++; 
    cb(doSomething1Error, doSomething1result); 
} 

,然後,你的測試用例會看這樣

describe('doSomething1 ', function() { 
    beforeEach(function(done) { 
    // reset global vars used by mock 
    doSomething1Error = null; 
    doSomething1result = []; 
    doSomething1CallCount = 0; 
    }); 

    it('is called once with error', function() { 
    doSomething1Error = 'User does not exist'; 
    // call you code under test (async.parallel([.....])) 

    // check that doSomething1CallCount == 1 
    // check that mock for handleError was called with 'User does not exist' error 
    }); 

})