Search code examples
javascripttestingmocha.jscode-reuse

Reuse scenarios by using mocha


Recently I've started to use JS and mocha.

I've wrote some tests already, but now I got to the point when I need to reuse my already written tests.

I've tired to look for "it" / "describe" reusing, but didn't find something useful...

Does anyone have some good example ?

Thanks


Solution

  • Considering that if you only do unit testing, you won't catch errors due to integration problems between your components, you have at some point to test your components together. It would be a shame to dump mocha to run these tests. So you may want to run with mocha a bunch of tests that follow the same general patter but differ in some small respects.

    The way I've found around this problem is to create my test functions dynamically. It looks like this:

    describe("foo", function () {
        function makeTest(paramA, paramB, ...) {
            return function () {
                // perform the test on the basis of paramA, paramB, ...
            };
        }
    
        it("test that foo does bar", makeTest("foo_bar.txt", "foo_bar_expected.txt", ...));
        it("test what when baz, then toto", makeTest("when_baz_toto.txt", "totoplex.txt", ...));
        [...]
    });
    

    You can see a real example here.

    Note that there is nothing that forces you to have your makeTest function be in the describe scope. If you have a kind of test you think is general enough to be of use to others, you could put it in a module and require it.