有没有办法在运行时获取当前的Mocha实例和编辑选项?

Ade*_*lin 12 javascript automation mocha.js

假设你有一个简单的摩卡测试:

describe("Suite", function(){
    it("test",function(doneCallback){
        // here be tests
    });
});
Run Code Online (Sandbox Code Playgroud)

在此测试中,我可以通过添加函数this.timeout(VALUE);内的任何位置来更改超时describe.

但是,除了该timeout值之外,还有许多其他Mocha选项可以从命令行或生成mocha.opts在test文件夹(./test/mocha.opts)中的文件中独占声明.

我想要的是在运行时更改其中一些选项(例如,reporter),而不是在命令行/ mocha.opts文件中.

根据我对可能性的研究,我发现有一篇文章解释了如何以编程方式使用mocha,这将允许在运行时更改这些选项,但是您需要自己创建Mocha实例,而在普通测试中则不会t可以直接访问Mocha实例.

那么,有没有办法Mocha从现有测试中获取实例并reporter在测试期间更改某些选项,例如在运行时?

我想有一个选项,不需要以Mocha任何方式修改源代码(我想我可以篡改Mocha实例来实现一种直接在Mocha构造函数中获取实例的方法).

Jan*_*tis 2

你不能。无需更改代码。

简而言之,mocha 是在您无法通过测试访问的范围内创建的。如果不详细说明,您范围内提供的对象无法更改您想要的选项。(你不能这样做:链接

但是有一种方法可以定义您自己的报告器并自定义每个测试的输出:

创建一个名为MyCustomReporter.js的文件:

'use strict';

module.exports = MyCustomReporter;

function MyCustomReporter (runner) {

    runner.on('start', function () {
        var reporter = this.suite.suites["0"].reporter;
        process.stdout.write('\n');

    });

    runner.on('pending', function () {
            process.stdout.write('\n  ');
    });

    runner.on('pass', function (test) {
        var reporter = this.suite.useReporter;
        if(reporter == 'do this') {
        }
        else if(reporter == 'do that'){
        }
        process.stdout.write('\n  ');
        process.stdout.write('passed');
    });

    runner.on('fail', function () {
        var reporter = this.suite.useReporter;
        process.stdout.write('\n  ');
        process.stdout.write('failed ');
    });

    runner.on('end', function () {
        console.log();
    });
}
Run Code Online (Sandbox Code Playgroud)

当你运行mocha时,将MyCustomReporter.js的路径作为reporter参数传递(不带.js),例如:

mocha --reporter "/home/user/path/to/MyCustomReporter"
Run Code Online (Sandbox Code Playgroud)

如果在默认脚本(lib/reporters 下)中找不到报告文件,默认的mocha 脚本实际上会尝试要求报告文件, github 链接

最后,在测试中,您可以传递一些参数来自定义报告器的输出:

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
      this.parent.reporter = 'do this';
    it('should return -1 when the value is not present', function() {
        this.runnable().parent.useReporter = 'do this';
        assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)