'parametrized tests with Mocha

How can I create parametrized tests with Mocha?

Sample use case: I have 10 classes, that are 10 different implementations of the same interface. I want to run the exact same suit of tests for each class. I can create a function, that takes the class as a parameter and runs all tests with that class, but then I will have all tests in a single function - I won't be able to separate them nicely to different "describe" clauses...

Is there a natural way to do this in Mocha?



Solution 1:[1]

Take a look at async.each. It should enable you to call the same describe, it, and expect/should statements, and you can pass in the parameters to the closure.

var async = require('async')
var expect = require('expect.js')

async.each([1,2,3], function(itemNumber, callback) {
  describe('Test # ' + itemNumber, function () {
    it("should be a number", function (done) {
      expect(itemNumber).to.be.a('number')
      expect(itemNumber).to.be(itemNumber)
      done()
    });
  });
callback()
});

gives me:

$ mocha test.js -R spec
  Test # 1
    ? should be a number 
  Test # 2
    ? should be a number 
  Test # 3
    ? should be a number 
  3 tests complete (19 ms)

Here's a more complex example combining async.series and async.parallel: Node.js Mocha async test doesn't return from callbacks

Solution 2:[2]

You do not need async package. You can use forEach loop directly:

[1,2,3].forEach(function (itemNumber) {
    describe("Test # " + itemNumber, function () {
        it("should be a number", function (done) {
            expect(itemNumber).to.be.a('number')
            expect(itemNumber).to.be(itemNumber) 
        });
    });
});

Solution 3:[3]

I know this was posted a while ago but there is now a node module that makes this really easy!! mocha param

const itParam = require('mocha-param').itParam;
const myData = [{ name: 'rob', age: 23 }, { name: 'sally', age: 29 }];

describe('test with array of data', () => {
    itParam("test each person object in the array", myData, (person) =>   {
    expect(person.age).to.be.greaterThan(20);
  })
})

Solution 4:[4]

Actually the mocha documentation specifies how to create what you want here

describe('add()', function() {
  var tests = [
    {args: [1, 2], expected: 3},
    {args: [1, 2, 3], expected: 6},
    {args: [1, 2, 3, 4], expected: 10}
  ];

  tests.forEach(function(test) {
    it('correctly adds ' + test.args.length + ' args', function() {
      var res = add.apply(null, test.args);
      assert.equal(res, test.expected);
    });
  });
 });

The answer provided Jacob is correct just you need to define the variable first before iterating it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis
Solution 2 HaaLeo
Solution 3 Mike
Solution 4 Jasper