2

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

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

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

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

  });   
});
4

2 回答 2

0

不,摩卡没有内置功能可以做到这一点,但是您可以通过使用操作系统中的标准管道来做一些其他的事情。

打开终端,输入命令

mocha TEST.js > report.txt

上面的命令只是将所有输出通过管道传输到 report.txt 文件。

您也可以尝试使用child_processnode 中的模块,在这里您几乎可以执行与命令行相同的操作,但使用的是纯 js。

*代码来自 node.js 文档

 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();
于 2013-10-24T07:09:00.283 回答
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
于 2018-10-17T11:48:28.510 回答