2012-02-03 268 views
7

我想知道是否有办法从node.js以编程方式执行mocha测试,以便我可以将单元测试与Cloud 9集成在一起。云9 IDE有当JavaScript文件被保存时,它会寻找一个具有相同名称的文件,以“_test”或“Test”结尾,并使用node.js自动运行。例如,它有一个自动运行的文件demo_test.js中的代码片段。使用摩卡云测试9,从node.js执行摩卡测试

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

有没有这样的事情可以用来运行摩卡测试?像摩卡(这).run()?

回答

12

要领以编程方式运行摩卡:

要求摩卡:

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

添加测试文件:

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

运行它!:

mocha.run(); 

添加链接功能来编程处理通过和失败的测试。在这种情况下,添加一个回调到打印结果:

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

您的里程可能会有所不同,但我炮制以下的一行而回,并一直担任我很好:

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