【问题标题】:Is it possible to define mocha tests asynchronously?是否可以异步定义 mocha 测试?
【发布时间】:2018-12-28 19:46:05
【问题描述】:

正如 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 个测试用例。

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

【问题讨论】:

    标签: javascript node.js asynchronous testing mocha.js


    【解决方案1】:

    我刚刚找到了方法。如果您使用 --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

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 2014-02-08
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多