简体   繁体   中英

How can I make a promise reject for testing?

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?

导致数据库条目或您的api发生某些更改,使db.users.count()调用失败。

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

    });
});    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM