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.

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.)

Good test design means that all tests should work independently of each other. See here: http://programmers.stackexchange.com/questions/64306/should-each-unit-test-be-able-to-be-run-independently-of-other-tests

Each test should have a setup and a teardown, should not have any effects on the other running tests, and shouldn't leave a footprint that impacts future tests.

As for your question, I don't know how to do that. You could provide the -bail command arg when running the tests to bail after the first fail, however.

I generally agree with Glen, but since you have a decent use case, you should be able to trigger node to exit with the process.exit() command. See http://nodejs.org/api/process.html#process_process_exit_code. You can use it like so:

process.exit(1);