简体   繁体   中英

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM