Vladimir.J.Nekiy
Vladimir.J.Nekiy

Reputation: 105

Reusing mocha test code

I'm developing a NodeJS application and use Mocha for unit testing.

Let's say i have two very similar test suits. In fact those are tests for two classes which implement the same interface.

For example:

suit_a.js

var A = require('./a');
describe(function () {
    var instance;
    beforeEach(function () {
        instance = new A();
    });
    it(function () {
        assert(instance.getSomeValue() === 1);
    });
});

suit_b.js

var B = require('./b');
describe(function () {
    var instance;
    beforeEach(function () {
        instance = new B({option: "option-value"});
    });
    it(function () {
        assert(instance.getSomeValue() === 1);
    });
});

Is there a way to remove code repetition? Is there a way to have two different test suits, using same assertion code, but with different configuration or something like that?

The only idea I have right now is to use some kind of source code generation, but I would like to avoid that if possible.

Upvotes: 3

Views: 1524

Answers (1)

CFrei
CFrei

Reputation: 3627

Move the inner function to an extra file and require it. In your case you need new A() and new B(...) extra, so either make them available outside or include them as a parameter to the require-result:

var t = require('innerTestGen');

var t1 = t.create(new A())
describe(t1);
var t2 = t.create(new B(...))
describe(t2);

Hope that helps?

Upvotes: 2

Related Questions