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.
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', _ => { // ... })
Mocha will run the tests in the order the describe calls execute.
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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With