Problem
I have multiple Mocha tests that perform the same actions, leading to code duplication. This impacts the maintainability of the code base.
var exerciseIsPetitionActive = function (expected, dateNow) {
var actual = sut.isPetitionActive(dateNow);
chai.assert.equal(expected, actual);
};
test('test_isPetitionActive_calledWithDateUnderNumSeconds_returnTrue', function () {
exerciseIsPetitionActive(true, new Date('2013-05-21 13:11:34'));
});
test('test_isPetitionActive_calledWithDateGreaterThanNumSeconds_returnFalse', function () {
exerciseIsPetitionActive(false, new Date('2013-05-21 13:12:35'));
});
What I'm Looking For
I'm seeking a method to consolidate my duplicated Mocha tests into a single one.
As an example, PHPUnit (and other testing frameworks) incorporate data providers. In PHPUnit, a data provider operates as follows:
<?php class DataTest extends PHPUnit_Framework_TestCase {
/**
* @dataProvider provider
*/
public function testAdd($a, $b, $c)
{
$this->assertEquals($c, $a + $b);
}
public function provider()
{
return array(
array(0, 0, 0),
array(0, 1, 1),
array(1, 0, 1),
array(1, 1, 3)
);
}
}
The data provider in this case injects parameters into the test, allowing the test to execute all cases efficiently - ideal for handling duplicated tests.
I'm curious to learn if Mocha has a similar feature or functionality, such as:
var exerciseIsPetitionActive = function (expected, dateNow) {
var actual = sut.isPetitionActive(dateNow);
chai.assert.equal(expected, actual);
};
@usesDataProvider myDataProvider
test('test_isPetitionActive_calledWithParams_returnCorrectAnswer', function (expected, date) {
exerciseIsPetitionActive(expected, date);
});
var myDataProvider = function() {
return {
{true, new Date(..)},
{false, new Date(...)}
};
};
What I've Explored
I've come across a technique called Shared Behaviors. However, it doesn't directly address the issue within a test suite; it only handles duplicated tests across different components.
The Question
Does anyone know how to implement data providers in Mocha?