Introduction
Testing checks whether the application achieves all the requirements, serves the user with expected functionality and the correct use cases. In other words, testing is done to check the behavior of the application. The entire code is divided into a few parts based on different properties. These units are called Tests. We are going to discuss how to generate tests dynamically in this article.
Dynamically generating tests
Suppose we initialize variables with any value in our application. In that case, the test cases will be static as we already know the values, and we need to test the same variables always. But what if the user gives input and the values are stored dynamically into the variables? So to test every possible input in a dynamic code, we choose dynamic tests.
Mocha provides us with functions like assert, describe that can be used to define suites and test cases to generate the tests dynamically. We can use plain ol’ JavaScript to generate dynamic tests similar to parameterized tests without any special syntax. Let’s learn how to generate dynamic tests throughout this example.
Using loop
const assert = require('assert');
function add(args) {
return args.reduce((prev, present) => prev + present, 0);
}
describe('add()', function () {
const tests = [
{args: [3, 2], expected: 5},
{args: [4, 2, 9], expected: 15},
{args: [3, 0, 7, 4], expected: 14}
];
tests.forEach(({args, expected}) => {
it(`correctly adds ${args.length} args`, function () {
const res = add(args);
assert.strictEqual(res, expected);
});
});
});
The code written above will produce three specs:
add()
✓ correctly adds 2 args
✓ correctly adds 3 args
✓ correctly adds 4 args
We imported assert in the above code and created a function add to add all the possible input given in tests in the describe function. The describe function groups the tests together because all the tests are written for the same function - “addition”. After all the tests are evaluated, they are checked individually using the it() method inside the forEach loop. If the expected result and the obtained result are equal, the test case is successful; otherwise, they are failed.
Using Individual parameters
Sometimes, the forEach loop might not give the correct results, so instead of that, we can directly pass the tests as parameters to generate them.
describe('add()', function () {
const testAdd = ({args, expected}) =>
function () {
const res = add(args);
assert.strictEqual(res, expected);
};
it('correctly adds 2 args', testAdd({args: [3, 2], expected: 5}));
it('correctly adds 3 args', testAdd({args: [4, 2, 9], expected: 15}));
it('correctly adds 4 args', testAdd({args: [3, 0, 7, 4], expected: 14}));
});
The above code is equivalent to the first code. The only difference is instead of using the forEach loop, we are passing all the tests as parameters individually using the it() method. Both the code will produce the same specs and same results.




