adam8810 adam8810 - 3 months ago 14
Node.js Question

How to Completely End a Test in Node Mocha Without Continuing

How do I force a Mochajs test to end completely without continuing on to the next tests. A scenario could be prevent any further tests if the environment was accidentally set to production and I need to prevent the tests from continuing.

I've tried throwing Errors but those don't stop the entire test because it's running asynchronously.

Answer

The kind of "test" you are talking about --- namely checking whether the environment is properly set for the test suite to run --- should be done in a before hook. (Or perhaps in a beforeEach hook but before seems more appropriate to do what you are describing.)

However, it would be better to use this before hook to set an isolated environment to run your test suite with. It would take the form:

describe("suite", function () {
    before(function () {
        // Set the environment for testing here.
        // e.g. Connect to a test database, etc.
    });

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

If there is some overriding reason that makes it so that you cannot create a test environment with a hook and you must perform a check instead you could do it like this:

describe("suite", function () {
    before(function () {
        if (production_environment)
            throw new Error("production environment! Aborting!");
    });

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

A failure in the before hook will prevent the execution of any callbacks given to it. At most, Mocha will perform the after hook (if you specify one) to perform cleanup after the failure.

Note that whether the before hook is asynchronous or not does not matter. (Nor does it matter whether your tests are asynchronous.) If you write it correctly (and call done when you are done, if it is asynchronous), Mocha will detect that an error occurred in the hook and won't execute tests.

And the fact that Mocha continues testing after you have a failure in a test (in a callback to it) is not dependent on whether the tests are asynchronous. Mocha does not interpret a failure of a test as a reason to stop the whole suite. It will continue trying to execute tests even if an earlier test has failed. (As I said above, a failure in a hook is a different matter.)