簡體   English   中英

在運行測試之前如何從mocha上的文件中讀取?

[英]How do you read from a file on mocha prior to running tests?

我目前正在對API運行測試 - 使用Mocha沒有問題。 測試數組存儲在變量中 - 文件頂部的“tests”。 我想從文本文件中讀取測試信息,並在運行測試之前將信息解析為變量(一次)。

我試過同步和異步使用before()(下面)

//Synchronously
describe("API Tests", function (done) {
    before(function(){
        tests = fs.readFileSync('./json.txt', 'utf8');
        tests = JSON.parse(tests);
    });
    for (var i = 0; i < tests.length; i++) {
        runTest(tests[i]);
    }
    done();
});

//Asynchronously
describe("API Tests", function () {
var tests = "";
before(function(){
    fs.readFile('./json.txt', 'utf8', function(err, fileContents) {
    if (err) throw err;
    tests = JSON.parse(fileContents);
    });
});

for (var i = 0; i < tests.length; i++) {
    runTest(tests[i]);
}});

節點返回一個錯誤,指出該文件不存在(它確實存在)。

另外,我試圖運行文件讀取(同步和異步),在回調時執行封裝描述(如下所示)。 似乎無法檢測到案件,返回“未找到任何測試”。

var tests;
fs.readFile('./json.txt', 'utf8', function(err, fileContents) {
if (err) throw err;
tests = JSON.parse(fileContents);

describe("API Tests", function () {
    for (var i = 0; i < tests.length; i++) {
        runTest(tests[i]);
    }
});
});

如何在運行Mocha之前讀取包含測試用例的文件? 我在Webstorm中使用Mocha。

異步版本是錯誤的,你需要一個傳遞done回調before ,否則鈎子將同步運行。 就像是

before(function(done){
    fs.readFile('./json.txt', 'utf8', function(err, fileContents) {
      if (err) throw err;
      tests = JSON.parse(fileContents);
      done();
    });
});

暫無
暫無

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

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