簡體   English   中英

當我在 Mocha 框架中調用助手 function 時,在我的 test.js 中調用它時返回 Undefined

[英]When I call helper function in Mocha framework, it returns Undefined when called in my test.js

我有我的 helper.js,我在其中定義了 function 以讀取目錄中的文件名:

module.exports.getfilenames= function(dirPath)
{
    console.log(dirPath);
    let files= fs.readdir(dirPath, function (err, files) {
    if (err)
        console.log(err);
      else {
        console.log("\nCurrent directory filenames:");
        files.forEach(file => {
          console.log(file); 
        })
        return files;
      }
    }) 
};

In test.js
I am calling helper function as:
describe('FILES', function()
{
     files=helper.getfilenames(dirPath);//dirPath is a value of path of directory
     it('GET FILES', function(done) {        
     console.log("reading files:"+ files);
     done();
  })
})

Output:

reading files: Undefined

請建議如何解決 test.js 中的文件 object?

fs.readdir是一個異步 function,您需要使用同步版本readdirSync

let files = fs.readdirSync(dirPath);
files.forEach(file => {
  console.log(file); 
})
return files;

否則,您可以使用異步版本,但需要進行一些代碼更改。

暫無
暫無

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

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