2012-02-03 267 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); 
}