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, thank you for a readable version of the above! 👍
this is really great thanks for the decaf version @dmkc!
Just what I was looking for, thanks @dmkc for the readable version.
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.)
Thanks a lot for this @ericprud. That is the whole point of testing: checking for results/outcomes!
Thanks for this! Just wanted to add that if you don't want to use process.on events, you can use mocha runner events!
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()
suiteRun.on('Mocha.Runner.constants.EVENT_SUITE_END', (code) => {
process.exit(suiteRun.stats.failures > 0)
});
The decaf version: