我如何承诺拒绝测试? [英] How can I make a promise reject for testing?

查看:31
本文介绍了我如何承诺拒绝测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个 db.js 来执行我所有的数据库调用.这是查询数据库的函数之一的示例.

I have a db.js set up to do all my database calls. 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);
    });
});

};

我对 JavaScript 和测试还很陌生.我已经使用 mocha 和 chai 测试它是否像这样解析:

I am pretty new to JavaScript and testing. I have used mocha and chai to test that it resolves like this:

describe('getUserCount', function() {
    it('should be fulfilled when called', function() {
        return db.getUserCount().should.be.fulfilled; 
    });
});

我如何测试承诺的拒绝部分.我必须使用类似 sinon 之类的东西还是有一些简单的方法可以使承诺失败?

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 存根,因此其他测试仍然可以通过.

I ended up using sinon stubs so the other test would still pass.

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

    });
});    

这篇关于我如何承诺拒绝测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆