How do I run a mocha test only after the prior asynchronous test has passed?

javascript, mocha.js, testing

Solution

Use the `--bail` option. Make sure you are using at least mocha 0.14.0. (I've tried it with older versions without success.)

First, there's nothing you need to do for mocha to run a test only after the previous one has finished. That's how mocha works by default. Save this to `test.js`:

describe("test", function () {
    this.timeout(5 * 1000); // Tests time out in 5 seconds.

    it("first", function (done) {
        console.log("first: do nothing");
        done();
    });

    it("second", function (done) {
        console.log("second is executing");
        // This test will take 2.5 seconds.
        setTimeout(function () {
            done();
        }, 2.5 * 1000);
    });

    it("third", function (done) {
        console.log("third is executing");
        // This test will time out.
    });

    it("fourth", function (done) {
        console.log("fourth: do nothing");
        done();
    });
});

Then execute it with:

mocha -R spec test.js

You will not see the fourth test start until:

- The first and second tests are finished.

- The third tests has timed out.

Now, run it with:

mocha -R spec --bail test.js

Mocha will stop as soon as test 3 fails.

Problem

Using the mocha javascript testing framework, I want to be able to have several tests (all asynchronous) only execute after the previously defined test has passed. I don't want to have to nest these tests within each other. ``` describe("BBController", function() { it("should save", function(done) {}); it("should delete", function(done) {}); }) ```

Original source