How to Completely End a Test in Node Mocha without Continuing

How to make Mochajs test finish completely without going to the next tests. The script could prevent any further tests if the environment was accidentally set up for production and I needed to prevent the tests from continuing.

I've tried throwing errors, but they don't stop the whole test, because it runs asynchronously.

+3


source to share


3 answers


The type of "test" you're talking about, which is verifying that the environment is set up correctly to run the test suite, must be done with a before

hook. (Or perhaps in beforeEach

, but before

it seems more appropriate to do what you describe.)

However, it would be better to use this hook before

to set up an isolated environment to run your test suite. It will 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 main reason why you cannot create a test environment with a hook, and you have to perform validation, you can do it like this:



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

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

      

Failure on the tag will before

prevent any callbacks passed in from being executed it

. At most, Mocha will execute a hook after

(if you specify one) to perform cleanup after a crash.

Note that if the host is before

asynchronous or doesn't matter. (And it doesn't matter if your tests are asynchronous.) If you write correctly (and call done

when ready, if it's asynchronous), Mocha will detect that the error occurred in the hook and will not run the tests.

And the fact that Mocha continues testing after you have a test failure (on a callback it

) is independent of whether the tests are asynchronous. Mocha does not interpret a test failure as causing the entire package to stop. It will continue trying to run tests even if the previous test failed. (As I said above, hook failure is a different matter.)

+6


source


I generally agree with Glen, but since you have a decent use case, you can start node to exit with the command process.exit()

. See http://nodejs.org/api/process.html#process_process_exit_code . You can use it like this:



process.exit(1);

      

+6


source


A good test design means that all tests should work independently of each other. See here: https://softwareengineering.stackexchange.com/questions/64306/should-each-unit-test-be-able-to-be-run-independently-of-other-tests

Each test should have setup and breaks, should not affect other current tests, and should not leave a mark that affects future tests.

As for your question, I don't know how to do this. However, you can provide the -bail command when running tests to lock after the first failure.

-2


source







All Articles