[英]How can I make a promise reject for testing?
I have a db.js set up to do all my database calls. 我设置了一个db.js来执行所有数据库调用。 This is an example of one of the functions that query the database. 这是查询数据库的功能之一的示例。
db.getUserCount = function () {
return new Promise (function (resolve, reject) {
db.users.count().then(function (result) {
resolve (result);
}, function(e) {
reject (e);
});
});
}; };
I am pretty new to JavaScript and testing. 我对JavaScript和测试非常陌生。 I have used mocha and chai to test that it resolves like this: 我已经使用mocha和chai来测试它的解析方式是这样的:
describe('getUserCount', function() {
it('should be fulfilled when called', function() {
return db.getUserCount().should.be.fulfilled;
});
});
How can I test the reject part of the promises. 我如何测试承诺的拒绝部分。 Do I have to use something like sinon or is there some simple way to make the promise fail? 我是否必须使用诸如sinon之类的东西,还是有一些简单的方法来使诺言失败?
导致数据库条目或您的api发生某些更改,使db.users.count()
调用失败。
I ended up using sinon stubs so the other test would still pass. 我最终使用了sinon存根,因此其他测试仍然可以通过。
describe('db.getUserCount rejection test', function() {
sinon.stub(db, 'getUserCount').returns(Q.reject(new Error(errorMessage)));
it('should be rejected when called', function() {
return db.getUserCount().should.be.rejected;
});
it.only('getUserCount responds with correct error message', function() {
return db.getUserCount().catch(function(err) {
expect(err.message).to.equal('Error could not connect to database');
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.