Parameterized Tests for Mocha

2.0.1 · active · verified Sun Apr 19

mocha-each is a utility for the Mocha testing framework that simplifies the creation of parameterized tests. It allows developers to define a single test case that runs multiple times with varying sets of input data, significantly reducing code duplication and enhancing test coverage. The current stable version is 2.0.1. While specific release cadence isn't explicitly stated, the project appears to be stable and maintained, with the latest version indicating ongoing support. Its primary differentiator is the seamless integration of data-driven testing within Mocha's existing `it` and `describe` syntax, making it straightforward to iterate over arrays of test data. A key feature is its guarantee that all parameterized test cases are executed, even if some individual cases fail, which is crucial for comprehensive test reporting. It also supports parameterization at the `describe` block level and handles asynchronous test cases effectively.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `mocha-each` to run a simple parameterized test for an `add` function with different input sets, verifying both valid and invalid arguments within a Mocha test suite.

const assert = require('assert');
const forEach = require('mocha-each');

function add(a, b) {
  return parseInt(a) + parseInt(b);
}

describe('add()', () => {
  forEach([
    [1, 1, 2],
    [2, -2, 0],
    [140, 48, 188]
  ])
  .it('adds %d and %d then returns %d', (left, right, expected) => {
    assert.equal(add(left, right), expected);
  });

  context('with invalid arguments', () => {
    forEach([
      [1, 'foo'],
      [null, 10],
      [{}, []]
    ])
    .it('adds %j and %j then returns NaN', (left, right) => {
      const value = add(left, right);
      assert(isNaN(value));
    });
  });
});

view raw JSON →