parametrized tests with Mocha

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);
  })
})

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) 
        });
    });
});

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


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.