[英]How to use Mocha with Promises/ES6 generators?
我想用Mocha
與ES6 generators
和任選的expect
。 經過研究,我構建了以下代碼片段:
describe('test', function() {
it('should not work', function() {
expect(function() {
return co(function*() {
yield Service.validate();
});
}).to.throw(new Error('error'));
});
});
Service.validate拋出new Error('error')
,這就是我所expect
。
module.exports = {
validate: function() {
return co(function*() {
// use yield to access db and so on
throw new Error('error');
});
}
};
但是,以下代碼將引發AssertionError: expected [Function] to throw 'Error: error'
。 有人可以幫忙嗎?
co
返回一個承諾,並且其中拋出的錯誤將變成已拒絕的承諾。 因此,您必須測試被拒絕的Promise,而不是例外。 此代碼有效:
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var co = require("co");
var expect = chai.expect;
chai.use(chaiAsPromised); // Register chai-as-promised with Chai.
describe('test', function() {
it('should not work', function() {
return expect(co(function*() {
throw new Error("testing failure!");
})).to.be.rejectedWith(Error, "testing failure!");
});
});
請注意,這如何return expect(...)
。 當您使用expect
檢驗promise時,它將返回一個promise,該promise可以返回給Mocha,以便它可以知道測試何時結束。
chai-promise可與co
結合使用。 co
返回了一個承諾,因此應相應地進行處理:
expect(co(function*() { ... })).to.be.rejectedWith(Error, 'error');
如果代碼不co
為基礎的,和發電機不產生承諾,發電機yield
可以直接進行測試:
expect(() => (function* () { ... })().next()).to.throw(Error, 'error');
或者,可以使用chai-generator來產生 to.yield
聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.