4

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?

4

3 回答 3

4

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.

于 2015-03-02T05:47:23.603 回答
3

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
于 2015-03-08T03:36:48.350 回答
2

A pattern I use in my Mocha/Chai/es6-promise tests is the following:

it('should do something', function () {

    aPromiseReturningMethod(arg1, arg2)
    .then(function (response) {
        expect(response.someField).to.equal("Some value")
    })
    .then(function () {
        return anotherPromiseReturningMethod(arg1, arg2)
    })
    .then(function (response) {
        expect(response.something).to.equal("something")
    })
    .then(done).catch(done)

})

The last line is odd looking, but calls Mocha's done on success or on error.

One problem is if the last then returns something, I then need to noop()* before both the then and the catch:

it('should do something', function () {

    aPromiseReturningMethod(arg1, arg2)
    .then(function (response) {
        expect(response.someField).to.equal("Some value")
    })
    .then(function () {
        return anotherPromiseReturningMethod(arg1, arg2)
    })
    .then(_.noop).then(done).catch(done)

})

*Lodash's noop().

Would love to hear any critiques of this pattern.

于 2015-04-03T18:22:17.523 回答