0

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?

nasoj1100
  • 528
  • 9
  • 15
  • It is a weird terminology to understand, the reject word, but I assume that you want to test for exceptions or errors. Testing is testing some condition so depending on the error condition or the exception case, modify your mocha test. – user2347763 Apr 25 '16 at 12:06
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572) (in `getUserCount`)! – Bergi Apr 25 '16 at 14:39
  • How do I go about that. Should I not be using the constructor or something? That is the only way I know how to make promises – nasoj1100 Apr 27 '16 at 13:09

2 Answers2

0

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

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
0

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

    });
});    
nasoj1100
  • 528
  • 9
  • 15