Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define Mocha tests programmatically and asynchronously?

I'm trying to integrate some programmatically generated tests with the Mocha test framework in node.js.

var Promise = require('promise');

var resolved = Promise.resolve(true);

suite("Synchronously defined suite", function() {
  test("Synchronously defined test", function() {
    return resolved;
  });
});

defer(function() {
  suite("Asynch DEFINED test", function() {
    suiteSetup(function() {
      console.log("Asynch setupSuite running...");
    });

    test("Asynch Test", function() {
      console.log("Async test running...");
      return resolved;
    });
  });
});

function defer(fn) {
  console.log("Calling defer...");
  setTimeout(fn, 100);
}

When I execute this I get:

$ mocha --ui tdd nested-test.js 
Calling defer...


  Synchronously defined suite
    ✓ Synchronously defined test


  1 passing (4ms)

It seems that Mocha requires that all "suite" functions be executed synchronously at module load time - deferred calls seem to be (silently) ignored (or the program exits before calling them).

like image 549
mckoss Avatar asked Nov 10 '22 06:11

mckoss


1 Answers

Here's what I've managed to come up with. It doesn't run underneath mocha, but as a stand-alone node program:

var Promise = require('promise');
var Mocha = require('mocha');

var resolved = Promise.resolve(true);
var rejected = Promise.reject(new Error("Failing test."));

defer(function() {
  console.log("Programmatic test suite creation.");
  var suite = new Mocha.Suite("Programatic Suite");
  var runner = new Mocha.Runner(suite);
  var reporter = new Mocha.reporters.Spec(runner);

  suite.addTest(new Mocha.Test("My test", function() {
    return resolved;
  }));

  suite.addTest(new Mocha.Test("My (failing) test", function() {
    return rejected;
  }));

  runner.run();
});

function defer(fn) {
  setTimeout(fn, 100);
}

When run it outputs:

$ node deferred-test.js 
Programmatic test suite creation.

Programatic Suite
  ✓ My test
  1) My (failing) test

  1 passing (7ms)
  1 failing

  1) Programatic Suite My (failing) test:
     Error: Failing test.
      at Object.<anonymous> (deferred-test.js:5:31)
      at node.js:935:3

I'd like to be able to include this test among all the (statically defined) mocha-run test suites in my application, however.

like image 84
mckoss Avatar answered Nov 15 '22 05:11

mckoss