asynchronouscallback的返回值(在unit testing中)

我正在尝试在我的node.js项目上执行jasmine-nodeunit testing。 我需要得到一个文件path的数组,然后将该数组传递给unit testing。 但是,因为这是asynchronous的,我必须使用callback,我不能返回数组。 我无法弄清楚如何将检索到的数组发送到unit testing。

这是我的代码:

module.exports = { results: [], walk: function(){ var nodeDir = require( "node-dir" ); nodeDir.files( __dirname + "/public/img", function( err, files ){ if ( err ){ throw err; } getData( files ); } ); }, getData: function( files ){ console.log( files ); results = files; } }; 

这是我的unit testing:

 var gallery = require( "./server" ); describe( "Gallery", function() { var picArray = [ "/gallery/public/img/dir1/lizard-248705_1280.jpg", "/gallery/public/img/dir1/loch-ness-151851_1280.png", "/gallery/public/img/dir1/sand-lizard-63185_1280.jpg", "/gallery/public/img/dir1/stegosaurus-24752_1280.png"]; it( "walks the images directory", function(){ expect(gallery.walk()).toEqual(picArray); }); }); 

这样你可以发回数组。 没有testing过,但它应该工作。

  module.exports = { results: [], walk: function(callback){ //Added callback argument var nodeDir = require( "node-dir" ); nodeDir.files( __dirname + "/public/img", function( err, files ){ if ( err ){ throw err; } callback(files); } ); } }; 

unit testing:

 var gallery = require( "./server" ); describe( "Gallery", function() { var picArray = [ "/gallery/public/img/dir1/lizard-248705_1280.jpg", "/gallery/public/img/dir1/loch-ness-151851_1280.png", "/gallery/public/img/dir1/sand-lizard-63185_1280.jpg", "/gallery/public/img/dir1/stegosaurus-24752_1280.png"]; it( "walks the images directory", function(done){ gallery.walk(function(files){ //Pass callback to walk //Your code here done(); //ends the async test }); }); });