【问题标题】:using mocha testing with cloud9, execute mocha tests from node.js使用 cloud9 进行 mocha 测试,从 node.js 执行 mocha 测试
【发布时间】:2012-11-15 02:02:49
【问题描述】:

我想知道是否有一种方法可以从 node.js 以编程方式执行 mocha 测试,以便我可以将单元测试与 Cloud 9 集成。cloud 9 IDE 有一个很好的功能,每当保存 javascript 文件时,它都会查找具有相同名称的文件,以“_test”或“Test”结尾,并使用 node.js 自动运行它。例如,它在一个文件 demo_test.js 中有这个代码 sn-p,它会自动运行。

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

有没有类似的东西可以用来运行 mocha 测试?像 mocha(this).run() 之类的东西?

【问题讨论】:

    标签: unit-testing node.js mocha.js


    【解决方案1】:

    以编程方式运行 mocha 的要点:

    需要摩卡:

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

    实例化调用构造函数:

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

    【讨论】:

      【解决方案2】:

      您的里程可能会有所不同,但我不久前炮制了以下单线,它对我很有帮助:

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

      【讨论】:

        猜你喜欢
        • 2017-10-26
        • 2023-03-08
        • 2017-08-03
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多