1

Testing the below in a Mocha/Chain start-up block, the code never waits as expected. Instead, the log reports on the start of creation, then logs from a test (not included), then reports the index creation is complete.

Should not Mocha not exit the before-each block until the Promise is reolved or rejected?

What have I missed?

module.exports.prototype.setup = function (term) {
    this.logger.info("Re-creating the index '%s'", $index);
    return this.client.indices.delete({
        index: $index,
        ignore: [404]
    }).then((err, resp, respcode) => {
        this.logger.info("Creating index '%s'", $index);
        return this.client.indices.create({
            index: $index,
            body: this.schemaBody
        });
    });
};
1
  • 3
    Promises are not blocking. They are asynchronous not synchronous. Commented Jun 24, 2016 at 18:54

2 Answers 2

2

You need to write an async test to test promises.

it("should do something", (done) => {
    setup("stuff").then((index) => {
        /* test index */
        done();
    });
});

You can also return a promise from the test and mocha will wait for it to resolve.

it("should do something", () => {
    return setup("stuff").then((index) => {
        /* test index */
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

How are you calling this code from the Mocha/Chai test? Is it in a beforeEach? From the Mocha Documentation you can do one of the following:

// [Option A] return a promise
beforeEach(() => {
  return setup("foo");
});

// [Option B]: add a `done` parameter, and call it when you are done
beforeEach((done) => {
  return setup("foo").then(() => {
     done();
  });
});

5 Comments

So often I forget that return statement that I'm surprised I don't check it more thoroughly....! Looked at the code for so long, I could not longer see it, thanks!
Yes it's very easy to forget ... done it many times myself! The return in the first case (Option A) is necessary. The return in the second case should be optional (Option B).
@LeeGee this is the part when you choose a right answer and maybe hand out some upvotes ;)
Ah! I've been trying to work out how SO works. If the question is good enough to answer, should you not also up-vote it?
@JamesLawson — I spent a lot of years with Perl, and its implicit return values. Only now do I miss them....!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.