Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

using mocha testing with cloud9, execute mocha tests from node.js

using mocha testing with cloud9, execute mocha tests from node.js

Problem

I was wondering if there is a way to execute Mocha tests programmatically from node.js so that I can integrate unit tests with Cloud 9. The cloud 9 IDE has a nice feature where whenever a javascript files is saved, it looks 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 code snippet in a file demo_test.js which automatically runs.

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

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

Problem courtesy of: MonkeyBonkey

Solution

The essentials to programmatically run mocha:

Require mocha:

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

Instatiate call the constructor:

var mocha = new Mocha();

Add test files:

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

Run it!:

mocha.run();

Add chained functions to programmatically deal with passed and failed tests. In this case add a call back 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);
});
Solution courtesy of: Shwaydogg

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

using mocha testing with cloud9, execute mocha tests from node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×