How can I make a promise reject for testing?

2019-09-14 18:48发布

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

};

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

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?

2条回答
走好不送
2楼-- · 2019-09-14 19:04

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

    });
});    
查看更多
够拽才男人
3楼-- · 2019-09-14 19:12

Make db.users.count() call to fail by either causing some change in database entry or in your api.

查看更多
登录 后发表回答