在mocha测试框架中,是否有可能将测试报告存储在本地文件中

时间:2013-10-24 04:34:06

标签: node.js mocha

我在我的节点应用程序中使用mocha框架。如果我使用mocha运行我的测试文件意味着我在终端中收到错误报告但我想将报告存储在本地文件中。我怎么能这样做。是否有内置mocha中的方法。

describe('Test with mocha', function(){

      it ('result should be true',function(done){

           var finalResult=false;      
           expect(finalResult).to.be(true);
           done();

  });   
});

2 个答案:

答案 0 :(得分:0)

没有内置的mocha功能可以做到这一点,但你可以通过使用操作系统标准的管道来做其他的事情。

打开终端,并发出命令

mocha TEST.js > report.txt

上面的命令只是将所有输出都传递给report.txt文件。

您也可以尝试使用来自节点的child_process模块,您可以在其中执行与命令行相同的操作,但在纯js中。

* 代码来自node.js docs

 var fs = require('fs'),
     spawn = require('child_process').spawn,
     out = fs.openSync('./out.log', 'a'),
     err = fs.openSync('./out.log', 'a');

 var child = spawn('prg', [], {
   stdio: [ 'ignore', out, err ]
 });

 child.unref();

答案 1 :(得分:0)

理想情况下,您可以使用mocha-junit-reporter并将输出写入XML文件。

mocha tests --recursive --reporter mocha-junit-reporter --reporter-options mochaFile=./myJUnitfile.xml

如果用本地文件表示简单的txt文件,那么我有一个示例代码供您扩展自己的实现。请注意,以下代码仅出于知识目的。它不处理许多报告程序事件,例如测试套件的开始和结束等,以及文件操作可能引发的异常。

有关报告者事件的完整列表,请参见https://github.com/mochajs/mocha/wiki/Third-party-reporters
下面的代码是上述链接中提供的示例代码的扩展。

// This code is extended on the orginal source present 
// at https://github.com/mochajs/mocha/wiki/Third-party-reporters

// my-file-reporter.js
const mocha = require('mocha');
const fs = require('fs');
const os = require("os");

module.exports = MyFileReporter;

function MyFileReporter(runner, options) {
  this._mochaFile = options.reporterOptions.mochaFile || process.env.MOCHA_FILE || 'test-results.txt';

  mocha.reporters.Base.call(this, runner);
  var passes = 0;
  var failures = 0;

  runner.on('start', function() {
    if (fs.existsSync(this._mochaFile)) {
      console.log('Removing existing test result file!');
      fs.unlinkSync(this._mochaFile);
    }
  }.bind(this));

  runner.on('pass', function(test){
    passes++;
    console.log('Pass: %s', test.fullTitle()); // Remove console.log statements if you dont need it (also below in code)
    fs.appendFileSync(this._mochaFile, 'Pass: ' + test.fullTitle() + os.EOL); // Note: Exception not handled
  }.bind(this));

  runner.on('fail', function(test, err){
    failures++;
    console.log('Fail: %s -- error: %s', test.fullTitle(), err.message);
    fs.appendFileSync(this._mochaFile, 'Fail: ' + test.fullTitle() + 'Error: ' + err.message + os.EOL); // Note: Exception not handled
  }.bind(this));

  runner.on('end', function(){
    console.log('Test Summary: %d/%d', passes, passes + failures);
    fs.appendFileSync(this._mochaFile, os.EOL + 'Test Summary: ' + passes + '/' + (passes + failures) + os.EOL); // Note: Exception not handled
  }.bind(this));
}

使用以下命令行(假定my-file-reporter.js位于执行此命令的同一文件夹中)

mocha tests --recursive --reporter my-file-reporter --reporter-options mochaFile=./myfile.txt