Skip to content

Instantly share code, notes, and snippets.

@cybertk
Created September 11, 2014 14:21
Show Gist options
  • Save cybertk/fff8992e12a7655157ed to your computer and use it in GitHub Desktop.
Save cybertk/fff8992e12a7655157ed to your computer and use it in GitHub Desktop.
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")
@TaslimOseni
Copy link

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

@AlexisTonneau
Copy link

AlexisTonneau commented Mar 23, 2022

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