当 chai.expect
断言失败时,
他们通常无法通过测试
并将阴性结果添加到报告中
对于测试运行程序(在本例中为 mocha
)。
但是,当我使用使用 co.wrap()
包装的生成器函数时,
如下所示,
奇怪的事情发生了:
当断言通过时,一切都运行良好。
然而,当断言失败时,测试就会超时。
co
如何与mocha
+chai
一起使用?
it('calls API and then verifies database contents', function(done) {
var input = {
id: 'foo',
number: 123,
};
request
.post('/foo')
.send(input)
.expect(201)
.expect({
id: input.id,
number: input.number,
})
.end(function(err) {
if (!!err) {
return done(err);
}
// Now check that database contents are correct
co.wrap(function *() {
var dbFoo = yield foos.findOne({
id: input.id,
});
continueTest(dbFoo);
})();
function continueTest(dbFoo) {
//NOTE when these assertions fail, test times out
expect(dbFoo).to.have.property('id').to.equal(input.id);
expect(dbFoo).to.have.property('number').to.equal(input.number);
done();
}
});
});
<小时/>
解决方案:
问题的出现是由于 co.wrap()
吞噬了 expect()
抛出的异常,不允许它冒泡到 需要的地方摩卡
找到它,正如下面@Bergi所指出的。
解决方案是使用 co()
而不是 co.wrap()
,并添加 .catch()
并传递done
回调,如下所示。
// Now check that database contents are correct
co(function *() {
var dbFoo = yield foos.findOne({
id: input.id,
});
continueTest(dbFoo);
}).catch(done);
最佳答案
co.wrap
捕获来自生成器的异常,并拒绝返回的 Promise。它“吞掉”了 continueTest
中的断言抛出的错误。顺便说一句,您可以直接调用 co(…)
,而不是使用 .wrap
并立即调用它。
co(function*() {
…
}).then(done, done); // fulfills with undefined or rejects with error
或
co(function*() {
…
done();
}).catch(done);
顺便说一句,要正确使用 co,您可以将所有异步函数放在一个生成器中:
it('calls API and then verifies database contents', function(done) {
co(function*() {
var input = {
id: 'foo',
number: 123,
};
yield request
.post('/foo')
.send(input)
.expect(201)
.expect({
id: input.id,
number: input.number,
})
.endAsync(); // assuming you've promisified it
// Now check that database contents are correct
var dbFoo = yield foos.findOne({
id: input.id,
});
expect(dbFoo).to.have.property('id').to.equal(input.id);
expect(dbFoo).to.have.property('number').to.equal(input.number);
}).then(done, done);
});
关于javascript - 将 mocha+chai 与 co 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31937330/