Mad Hollander Mad Hollander - 6 months ago 42
Javascript Question

Conditional mocha test

I use mocha for some integration testing and have many test sets.
All of them have kind of initialization tests per each set. When such tests are failed, the rest from set should not be run at all, because all of them will fail for sure.
The thing is that I can't avoid such initialization test, because part of the code/environment is generated by some tool which does not guarantee any correct result.

Is it possible to implement this using mocha ?

Answer

Using the BDD interface, the normal way to do this with Mocha is to put anything that sets up the testing environment into before or beforeEach:

describe("foo", function () {
    describe("first", function () {
        before(function () {
            // Stuff to be performed before all tests in the current `describe`.
        });

        beforeEach(function () {
            // Stuff to perform once per test, before the test.
        });

        it("blah", ...
        // etc...
    });

    describe("second", function () {
        before(function () {
            // Stuff to be performed before all tests in the current `describe`.
        });

        beforeEach(function () {
            // Stuff to perform once per test, before the test.
        });

        it("blah", ...
        // etc...
    });
});

If the before or beforeEach that a test depends on fails, then the test is not run. Other tests that don't depend on it will still run. So in the example above if the callback passed to before in the describe named first fails, the tests in the describe named second won't be affected at all and will run, provided that their own before and beforeEach callbacks don't fail.

Other than this, Mocha is designed to run tests that are independent from each other. So if one it fails, then the others are still run.

Comments