Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Promises in Mocha

I'm using this polyfill for ES6 promises and Mocha / Chai.

My assertions for the promises are not working. The following is a sample test:

it('should fail', function(done) {
    new Promise(function(resolve, reject) {
        resolve(false);
    }).then(function(result) {
        assert.equal(result, true);
        done();
    }).catch(function(err) {
        console.log(err);
    });
});

When I run this test it fails due to timeout. The assertion failure that was thrown in the then block is caught in the catch block. How can I avoid this and just throw it straight to Mocha?

I could just throw it from the catch function, but then how would I make assertions for the catch block?

like image 814
connorbode Avatar asked Jan 08 '23 19:01

connorbode


2 Answers

If your Promise has a failure, it will only call your catch callback. As a result, Mocha's done callback is never called, and Mocha never figures out that the Promise failed (so it waits and eventually times out).

You should replace console.log(err); with done(err);. Mocha should automatically display the error message when you pass an error to the done callback.

like image 152
Nick McCurdy Avatar answered Jan 19 '23 20:01

Nick McCurdy


I ended up solving my problem by using Chai as Promised.

It allows you to make assertions about the resolution and rejections of promises:

  • return promise.should.become(value)
  • return promise.should.be.rejected
like image 40
connorbode Avatar answered Jan 19 '23 18:01

connorbode