首页 文章

摩卡的ES6承诺

提问于
浏览
4

我正在使用this polyfill for ES6 promises和Mocha / Chai .

我对这些承诺的断言不起作用 . 以下是一个示例测试:

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);
    });
});

当我运行此测试时,由于超时而失败 . 在块中引发的断言失败在catch块中被捕获 . 我怎么能避免这种情况,直接把它扔到摩卡?

我可以从catch函数中抛出它,但是我如何为catch块进行断言?

3 回答

  • 2

    如果您的Promise失败,它只会调用您的catch回调 . 结果,Mocha的完成回调从未被调用,并且Mocha从未发现Promise失败(因此它等待并最终超时) .

    您应该将 console.log(err); 替换为 done(err); . 将错误传递给完成回调时,Mocha应自动显示错误消息 .

  • 4

    我最终使用Chai as Promised解决了我的问题 .

    它允许您对承诺的解决和拒绝做出断言:

    • return promise.should.become(value)

    • return promise.should.be.rejected

  • 3

    我在Mocha / Chai / es6-promise测试中使用的模式如下:

    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)
    
    })
    

    最后一行很奇怪,但是在成功或出错时调用了Mocha .

    一个问题是如果最后一个返回一些东西,那么我需要在 thencatch 之前使用noop()*:

    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的noop() .

    很想听到对这种模式的批评 .

相关问题