使用cloud9的摩卡testing,从node.js执行摩卡testing

我想知道是否有办法从node.js以编程方式执行mochatesting,以便我可以将unit testing与Cloud 9集成在一起。云9 IDE具有很好的function,只要保存javascript文件,它就会查找带有相同的名称,以“_test”或“Test”结尾,并使用node.js自动运行。 例如,它有一个自动运行的文件demo_test.js中的代码片段。

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

有没有这样的事情,我可以用来运行摩卡testing? 像摩卡(this).run()?

以编程方式运行摩卡的要点:

要求摩卡:

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

Instatiate调用构造函数:

 var mocha = new Mocha(); 

添加testing文件:

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

运行!:

 mocha.run(); 

添加链接函数以编程方式处理通过和失败的testing。 在这种情况下,添加callback打印结果:

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

你的里程可能会有所不同,但是我后来制作了下面的一行,它给了我很大的帮助:

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

此外,如果您希望以Cloud9预期的asyncjs格式输出,则需要提供特殊的记者。 下面是一个简单的记者看起来很简单的例子:

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