首页 > 解决方案 > 是否可以异步定义 mocha 测试?

问题描述

正如 mocha 文档中所指出的,可以动态生成测试:

var assert = require('chai').assert;

function add() {
  return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
    return prev + curr;
  }, 0);
}

describe('add()', function() {
  var tests = [
    {args: [1, 2],       expected: 3},
    {args: [1, 2, 3],    expected: 6},
    {args: [1, 2, 3, 4], expected: 10}
  ];

  tests.forEach(function(test) {
    it('correctly adds ' + test.args.length + ' args', function() {
      var res = add.apply(null, test.args);
      assert.equal(res, test.expected);
    });
  });
});

我遇到的问题是我想根据异步函数的结果生成测试。像这样的东西:

describe('add()', function() {
  asyncFunctionThatReturnsAPromise()
    .then(tests => {
      tests.forEach(function(test) {
        it('correctly adds ' + test.args.length + ' args', function() {
          var res = add.apply(null, test.args);
          assert.equal(res, test.expected);
        });
      });
    });
});

但是,执行时会产生 0 个测试用例。

是不支持异步定义测试,还是有办法做到这一点?

标签: javascriptnode.jsasynchronoustestingmocha.js

解决方案


我刚刚找到了怎么做。如果您使用--delay标志执行 mocha,run()将在全局范围内定义,并且您的测试套件在被调用之前不会执行run()。这是一个例子:

describe('add()', function() {
  asyncFunctionThatReturnsAPromise()
    .then(tests => {
      tests.forEach(function(test) {
        it('correctly adds ' + test.args.length + ' args', function() {
          var res = add.apply(null, test.args);
          assert.equal(res, test.expected);
        });
      });
      run();
    });
});

这是文档:https ://mochajs.org/#delayed-root-suite


推荐阅读