Using mocha testing with the cloud9, execute mocha tests from node.js

I was wondering if there is a way to do mocha tests programmatically from node.js so that I can integrate unit tests with cloud 9. Cloud 9 IDE has a nice function where whenever javascript files are saved it searches for a file with the same name ending with either "_test" or "Test" and runs it automatically using node.js. For example, it has this piece of code in the demo_test.js file that starts automatically.

if (typeof module !== "undefined" && module === require.main) { require("asyncjs").test.testcase(module.exports).exec() } 

Is there something like this that I could use to run a mocha test? Something like mocha (this) .run ()?

+7
source share
2 answers

The need to launch mocha programmatically:

Require mocha:

 var Mocha = require('./'); //The root mocha path (wherever you git cloned //or if you used npm in node_modules/mocha) 

Program the call with the constructor:

 var mocha = new Mocha(); 

Add test files:

 mocha.addFile('test/exampleTest'); // direct mocha to exampleTest.js 

Run it !:

 mocha.run(); 

Add chain functions for the software solution of passed and failed tests. In this case, add a callback to print the results:

 var Mocha = require('./'); //The root mocha path var mocha = new Mocha(); var passed = []; var failed = []; mocha.addFile('test/exampleTest'); // direct mocha to exampleTest.js mocha.run(function(){ console.log(passed.length + ' Tests Passed'); passed.forEach(function(testName){ console.log('Passed:', testName); }); console.log("\n"+failed.length + ' Tests Failed'); failed.forEach(function(testName){ console.log('Failed:', testName); }); }).on('fail', function(test){ failed.push(test.title); }).on('pass', function(test){ passed.push(test.title); }); 
+12
source

Your mileage may vary, but I came up with the following single-line snapshot and it served me well:

 if (!module.parent)(new(require("mocha"))()).ui("exports").reporter("spec").addFile(__filename).run(process.exit); 

In addition, if you want it to be displayed in the asyncjs format that Cloud9 expects, you need to provide a special reporter. Here is a really simple example of what a simple reporter looks like:

 if (!module.parent){ (new(require("mocha"))()).ui("exports").reporter(function(r){ var i = 1, n = r.grepTotal(r.suite); r.on("fail", function(t){ console.log("\x1b[31m[%d/%d] %s FAIL\x1b[0m", i++, n, t.fullTitle()); }); r.on("pass", function(t){ console.log("\x1b[32m[%d/%d] %s OK\x1b[0m", i++, n, t.fullTitle()); }); r.on("pending", function(t){ console.log("\x1b[33m[%d/%d] %s SKIP\x1b[0m", i++, n, t.fullTitle()); }); }).addFile(__filename).run(process.exit); } 
+1
source

All Articles