How can I dynamically generate test cases in javascript/node?
Yes you can dynamically created test suites with cases using Mocha. I have installed mocha globally npm install -g mocha
and I use should.
var should = require('should');
var foo = 'bar';
['nl', 'fr', 'de'].forEach(function(arrElement) {
describe(arrElement + ' suite', function() {
it('This thing should behave like this', function(done) {
foo.should.be.a.String();
done();
});
it('That thing should behave like that', function(done) {
foo.should.have.length(3);
done();
});
});
});
If you want to dynamically create It()
tests using data obtained asynchronously, you can (ab)use the before()
hook with a placeholder It()
test to ensure mocha waits until before()
is run. Here's the example from my answer to a related question, for convenience:
before(function () {
console.log('Let the abuse begin...');
return promiseFn().
then(function (testSuite) {
describe('here are some dynamic It() tests', function () {
testSuite.specs.forEach(function (spec) {
it(spec.description, function () {
var actualResult = runMyTest(spec);
assert.equal(actualResult, spec.expectedResult);
});
});
});
});
});
it('This is a required placeholder to allow before() to work', function () {
console.log('Mocha should not require this hack IMHO');
});