Erik B
Erik B

Reputation: 42554

Is it possible to define mocha tests asynchronously?

As pointed out in the mocha documentation, it's possible to dynamically generate tests:

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);
    });
  });
});

The problem I'm having is that I want to generate tests based on the result of an asynchronous function. Something like this:

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);
        });
      });
    });
});

However, that results in 0 test cases when executed.

Is defining tests asynchronously simply not supported, or is there a way to do this?

Upvotes: 1

Views: 293

Answers (1)

Erik B
Erik B

Reputation: 42554

I just found how to do it. If you execute mocha with the --delay flag, run() will be defined in the global scope and your test suite will not execute until run() is called. Here's an example:

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();
    });
});

Here's the documentation: https://mochajs.org/#delayed-root-suite

Upvotes: 1

Related Questions