Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 945
aaaidan Avatar asked Dec 09 '16 12:12

aaaidan


People also ask

How do I run a specific test file in mocha?

Run a Single Test File Using the mocha cli, you can easily specify an exact or wildcarded pattern that you want to run. This is accomplished with the grep option when running the mocha command. The spec must have some describe or it that matches the grep pattern, as in: describe('api', _ => { // ... })

Does Mocha run tests in order?

Mocha will run the tests in the order the describe calls execute.


1 Answers

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();
    });
});
like image 81
ThomasThiebaud Avatar answered Nov 14 '22 23:11

ThomasThiebaud