Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) {});
})
like image 374
Tim Lind Avatar asked Nov 27 '13 14:11

Tim Lind


People also ask

Do Mocha tests run sequentially?

It has a very simple interface for testing both synchronous and asynchronous code. Mocha. js executes tests in a sequential/serial order to provide flexible and accurate reporting, while also mapping uncaught exceptions to their respective test cases.

How do I run a specific test file in Mocha?

Run a Single Test File Using the mocha cli, you can easily specify an exact or wildcarded pattern that you want to run. This is accomplished with the grep option when running the mocha command. The spec must have some describe or it that matches the grep pattern, as in: describe('api', _ => { // ... })

How do you test async in Mocha?

Writing Asynchronous Tests with Mocha. To indicate that a test is asynchronous in Mocha, you simply pass a callback as the first argument to the it() method: it('should be asynchronous', function(done) { setTimeout(function() { done(); }, 500); });

How do you skip a Mocha test?

You can skip tests by placing an x in front of the describe or it block, or placing a . skip after it. describe('feature 1', function() {}); describe.


1 Answers

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:

  1. The first and second tests are finished.
  2. 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.

like image 83
Louis Avatar answered Nov 15 '22 06:11

Louis