2015-09-26 172 views
2

我正在嘗試在我的node.js項目上執行jasmine-node單元測試。我需要獲得一組文件路徑,然後將該數組傳遞給單元測試。但是,由於這是異步的,我必須使用回調,並且我不能返回數組。我無法弄清楚如何將檢索到的數組發送到單元測試。異步回調返回值(在單元測試中)

這裏是我的代碼:

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

,這裏是我的單元測試:

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

回答

0

這樣你就可以在陣列送回去。沒有測試過,但它應該可以工作。

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

單元測試:

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 
     }); 
    }); 
}); 
+0

謝謝!這工作。儘管我起初有點麻煩,因爲'gallery.walk()'沒有按照與picArray相同的順序發回數組,所以我仍然遇到錯誤。我不得不傳入'files.sort()'。 –