0

Here's the simple problem I'm struggling with. In the first example, no tests are run; whereas in the second one, two tests are run as expected.

Does not work as expected: // testData gets populated inside before here

// test.js
const assert = require('assert');
const forEach = require('mocha-each');

describe('compare()', () => {

    testData = [];

    before(function (done) {
        testData = [[1, 1], [2, 2]];
        done();
    });

    forEach(testData)
        .it('compares %d and %d', (baseline, actual) => {
            assert(baseline == actual);
        });

});

Works as expected: // testData is used as a hardcoded array here

// test.js
const assert = require('assert');
const forEach = require('mocha-each');

describe('compare()', () => {

    forEach([[1, 1], [2, 2]])
        .it('compares %d and %d', (baseline, actual) => {
            assert(baseline == actual);
        });

});

I do not understand why the modified value of testData is not taken by it in the first example.

Akshay Maldhure
  • 787
  • 2
  • 19
  • 38

1 Answers1

0

The problem is with how mocha sets up the test suite. The callback function in before function gets registered but does not gets executed before the mocha-each's foreach function.

Related issue - Dynamically load test parameters?

However, to have a parameterised test, you might not need a library, a simple preloaded array would work - Parameterized test in mocha. Although, the difference is there is one test with multiple asserts.

Demo - parameterized mocha tests

rvisharma
  • 36
  • 1
  • As I can see, there are multiple code example in the links you have shared and I'm relatively new to Node.js, so I would really appreciate if you could tweak the non-working code I've shared in my post. – Akshay Maldhure Jan 09 '19 at 12:59