Mocha中的ES6 Promises

4
我正在使用这个ES6 promises的polyfill和Mocha / Chai。
我的关于promises的断言没有起作用。以下是一个示例测试:
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);
    });
});

当我运行这个测试时,由于超时而失败。在then块中抛出的断言失败被catch块捕获。我该如何避免这种情况并直接将其抛给Mocha?我可以从catch函数中直接抛出它,但是我如何为catch块做出断言呢?

1
你有没有查看这个 - thefourtheye
你的 catch 应该是 console.log(err);done(err); 吗? - mido
@thefourtheye 承诺断言正是我所需要的。谢谢,这是一个很好的资源。 - connorbode
@mido22,问题在于对 Promise 拒绝的断言。但是,正如上面 @thefourtheye 所说,Mocha 显然已经内置了这个功能。 - connorbode
如果您断言 Promise 成功并且不需要再进行其他断言,那么您可以直接返回 Promise 的值而无需调用 .then().catch()。这个回答解决了您的问题吗? - Nick McCurdy
3个回答

4

如果你的 Promise 失败了,它只会调用 catch 回调函数。因此,Mocha 的 done 回调函数永远不会被调用,Mocha 永远无法知道 Promise 失败了(所以它会等待并最终超时)。

你应该将 console.log(err); 替换为 done(err);。当你向 done 回调传递错误时,Mocha 应该自动显示错误消息。


我该如何对 Promise 所拒绝的内容进行断言? - connorbode
你是什么意思?这个 Promise 应该成功还是失败?如果它应该成功,只要确保不会发生拒绝,我不明白为什么你需要断言任何关于拒绝的内容。 - Nick McCurdy
因为您希望对拒绝承诺的条件进行断言。 - connorbode

3

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

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

  • return promise.should.become(value)
  • return promise.should.be.rejected

你好,能否提供使用chai的代码,如之前承诺的那样? - Manoj

2
我在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的done函数。

一个问题是如果最后一个then返回了某些内容,那么我需要在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()函数。

非常愿意听取任何对这种模式的批评。


个人而言,在测试用例的任何onFullFilled处理程序中,我不会返回任何内容。但为了防止返回值,.then(done.bind(null, null), done) 对我来说似乎更加简洁。 - Pomin Wu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接