Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create mocha test/suite at runtime
require('chai').should()
Mocha = require 'mocha'
Test = Mocha.Test
Suite = Mocha.Suite
mocha = new Mocha
suite = Suite.create mocha.suite, 'I am a dynamic suite'
suite.addTest new Test 'I am a dynamic test', ->
true.should.equal true
mocha.run () ->
console.log("done")
@dmkc

This comment has been minimized.

Copy link

@dmkc dmkc commented Sep 29, 2015

The decaf version:

var Mocha = require('mocha');
var Chai = require('chai');
var Test = Mocha.Test;
var expect = Chai.expect;

var mochaInstance = new Mocha();
var suiteInstance = Mocha.Suite.create(mochaInstance.suite, 'Test Suite');

suiteInstance.addTest(new Test('testing tests', function(){
  expect(2).to.equal(2);
}))

mochaInstance.run();
@9662

This comment has been minimized.

Copy link

@9662 9662 commented Aug 24, 2016

@dmkc, thank you for a readable version of the above! 👍

@oshalygin

This comment has been minimized.

Copy link

@oshalygin oshalygin commented Feb 9, 2017

this is really great thanks for the decaf version @dmkc!

@lukeshiru

This comment has been minimized.

Copy link

@lukeshiru lukeshiru commented Mar 1, 2017

Just what I was looking for, thanks @dmkc for the readable version.

@ericprud

This comment has been minimized.

Copy link

@ericprud ericprud commented Apr 4, 2018

Most workflows look at the exit code to see if tests were successful so it's highly advisable to process.exit with a non-zero value if any tests failed.

var Mocha = require('mocha');
var Chai = require('chai');
var Test = Mocha.Test;
var expect = Chai.expect;

var mochaInstance = new Mocha();
var suiteInstance = Mocha.Suite.create(mochaInstance.suite, 'Test Suite');

suiteInstance.addTest(new Test('testing tests', function(){
  expect(1).to.equal(2); // note testing 1 === 2 should fail
}))

var suiteRun = mochaInstance.run()
process.on('exit', (code) => {
  process.exit(suiteRun.stats.failures > 0)
});

This works with asynchronous tests (e.g. addTest called in a .then) as well.
I fiddled with embedding it in the suite's afterAll but saw no advantage.

suiteInstance.afterAll(function () {
  process.on('exit', (code) => {
    process.exit(suiteRun.stats.failures > 0)
  })
})

(Exiting directly from the afterAll truncates the error report.)

@TaslimOseni

This comment has been minimized.

Copy link

@TaslimOseni TaslimOseni commented May 9, 2019

Thanks a lot for this @ericprud. That is the whole point of testing: checking for results/outcomes!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment