How can I make a promise reject for testing?

2019-09-14 18:58发布

问题:

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?

回答1:

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



回答2:

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

    });
});