async operations in Mocha (III.)

In notebook:
Work Notes
Created at:
2015-11-27
Updated:
2015-12-02
Tags:
The wrong way to test async operations with Mocha was to separate the before (when) and it (then) cases, and add the ​done​ parameter to the it assertions.
It works fine for small modules where despite being async everything executes (almost) immediattely.

The other day I decided to test a real Mongo db operations instead of stubbing out the driver (another story) and this approach did not work.

Instead, you I had to merge the when and then cases into one and do the expections on the Promise/callback results:
  context("it's called with whatever", function () {
    it("resolves promise", function (done) {
        subject("hats").then(function (myresult) {
            expect(myresult).to.equal("pants");
            done();
        });
    });
});

Even better, with chai-as-promised

you get better feedback on the assertions this way:
  context("it's called with whatever", function () {
    it("resolves promise", function (done) {
        expect(subject("pants")).to.eventually.equal("pants").notify(done);
    });
});
or just:
  context("search with keyword", function () {
    it("finds with keyword", function () {
        return expect(subject("pants")).to.eventually.equal("pantssss");
    });
});
previously it would look like this (the wrong way):
  // don't do this!
context("it's called with whatever", function(){
    before(function(){
        subject("hats").then(acallback);
    });
    it("resolves promise", function(done){
        expect(acallback.args[0][0]).to.equal("pants");
        done();
    });
});