簡體   English   中英

使用回調對功能進行單元測試

[英]Unit testing a function with callbacks

我在node.js中有一個功能:

fs.readdir(filesPath, function(err, items) {

    items.forEach(function(filename){


        fs.readFile(path.join(filesPath,filename), {encoding: 'utf-8'}, function (err,data){

        //do some calculations with data from each file, the result is an object 'finalOutput'


    fs.stat(path.join(__dirname,'output.csv'), function (err, stat) {
        //check if file exists

            fs.appendFile(path.join(__dirname,'output.csv'), csv, function (err) {
            // append output to csv 
    });
}
        else {
            //create file

            fs.writeFile(path.join(__dirname,'output.csv'), fields, function (err, stat) {
            if (err) console.log(err);
            console.log('File saved');
    });
}
});



   })
  })
});

我想對'finalOutput'變量,文件的內容(例如,如果文件為空,則輸出應為X等)以及輸出文件的存在進行測試。 但是,當我運行npm test(我正在使用mocha和chai時,出現'TypeError:無法讀取上下文中未定義的屬性'to')

這是我要運行的測試的示例:

var chai = require('chai'),
expect = chai.expect,
mypreviouscode = require('./mypreviouscode');

describe('test1', function() {
it('There output should always exist', function() {
expect(finalOutput.to.exist);
});
});

expect(finalOutput).to.exist

有在finalOutput對象未to.exist,這是存在於由柴返回的對象expect的功能。

話雖如此,您的測試仍將失敗,因為您的錯誤告訴您finalOutput對象不存在(未定義)。 如果要有一個全局的finalOutput對象,則必須在代碼中聲明它。 您可以這樣執行global.finalOutput = finalOutput (我想您是用let finalOuputconst finalOutputvar finalOutput

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM