aaaidan
aaaidan

Reputation: 315

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

I'm currently running tests on an API - which run with no issues using Mocha. The test array is stored in a variable - "tests" at the top of the file. I'm would like to read the test information from a text file and parse the information into a variable prior to running the tests (once).

I've tried to use before() both synchronously and asynchronously (below)

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

Node returns an error stating the file does not exist (which it does).

Additionally I have tried to run the file read (both synchronously and asynchronously), executing encapsulating the describe upon callback (as per below). It seems not to be able to detect the cases, returning "No tests were found".

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

How do I read a file containing test cases prior to running Mocha? I'm using Mocha in Webstorm.

Upvotes: 6

Views: 8050

Answers (1)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

The asynchronous version is wrong, you need to pass a done callback to before otherwise the hook will run synchronously. Something like

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

Upvotes: 13

Related Questions