Created
September 11, 2014 14:21
-
-
Save cybertk/fff8992e12a7655157ed to your computer and use it in GitHub Desktop.
Create mocha test/suite at runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
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)
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just what I was looking for, thanks @dmkc for the readable version.