繁体   English   中英

获取给定测试的Mocha`describe`调用列表

[英]Get a list of mocha `describe` calls for a given test

有没有一种方法来获取传递来describe的消息数组?

我想根据下面的describe调用中作为消息传递的值动态创建testList数组。

示例测试

 <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.min.css" rel="stylesheet"/> <div id="mocha"></div> <script> mocha.setup('bdd'); </script> <script> mocha.checkLeaks(); //mocha.globals(['jQuery']); </script> <script> var expect = chai.expect; var testList = ['methodTrue', 'methodFalse', 'methodIdentity']; var testObject = { methodTrue: function () {return true;}, methodFalse: function () {return false;}, methodIdentity: function (n) {return n;} } describe('testObject', function () { describe('methodTrue', function () { it('should be a method', function () { expect(testObject.methodTrue).to.be.a('function'); }); }); describe('methodFalse', function () { it('should be a method', function () { expect(testObject.methodFalse).to.be.a('function'); }); }); describe('methodIdentity', function () { it('should be a method', function () { expect(testObject.methodIdentity).to.be.a('function'); }); }); it('should have a method for every test', function () { Object.keys(testObject).forEach(function (v, i) { expect(testList.indexOf(v), 'no test for ' + v).to.be.above(-1); }); }); }); mocha.run(); </script> 

您可能会看一下Mocha的来源并弄清楚如何使用测试套件。 但是,这是一种不依赖于了解内部原理的方法,并且即使内部结构发生变化也不会中断。 该策略是用您自己的函数替换describe ,该函数记录传递给它的内容,以便以后使用。 我在命令行上使用过Mocha,但在要在Node中运行的套件中与要在浏览器中运行的套件中进行此操作之间没有什么区别。

var blocks = [];

function wrapperDescribe() {
    // It is generally unsafe to just leak `arguments` objects. So we
    // slice it to make a copy before pushing it into `blocks`.
    var args = Array.prototype.slice.call(arguments);
    blocks.push(args);
    describe.apply(this, args);
}

(function () {
    // We do not do this at the top level because it would modify a
    // global used by all Mocha files. Whether or not you do want this
    // depends on the needs to you project.
    var describe = wrapperDescribe;

    function fn () {}

    describe("one", function () {
        it("test 1", fn);
        it("test 2", fn);
    });

    describe("two", function () {
        it("test 1", fn);
        it("test 2", fn);
    });
}());

console.log(blocks);

输出:

$ ./node_modules/.bin/mocha 
[ [ 'one', [Function] ], [ 'two', [Function] ] ]


  one
    ✓ test 1
    ✓ test 2

  two
    ✓ test 1
    ✓ test 2


  4 passing (6ms)

在运行测试之前输出数组,这对于Mocha是正常的。 (Mocha首先读取所有测试,执行所有describe回调,然后运行测试。)

为了使此功能仅在describe块的子集上起作用,您不能覆盖describe ,而是根据需要直接调用wrapperDescribe

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM