Charlie Fish
Charlie Fish

Reputation: 20496

Mocha Unit Test Error Handling from Library

I have the following code below that basically gets a user from a database. The code below is using Dynamoose but I'm assuming there is something similar in many other libraries and packages.

User.get(searchid, function(err, user) {
    if (err) {
        console.log(err);
        return res.send('error');
    } else {
        //DO LOGIC
    }
});

I have written unit tests to handle all the logic inside the else statement above. But I'm trying to figure out if there is a way to write unit tests to handle the if (err) section of the code. Basically I want to write unit tests to make sure that if there is an error it returns the correct stuff tho I would be up for any suggestions of other tests I should write. How can I write tests in this case and cover this code with unit tests?

Upvotes: 1

Views: 166

Answers (1)

Boris Charpentier
Boris Charpentier

Reputation: 3545

You should mock User.get to make it execute the callback directly, with the parameters you want.

To do that, you may have multiple possibility depending on your test setup.

I use rewire https://github.com/jhnns/rewire

If your code look like :

//myCode.js
var User = require('./model/User');

module.exports = function(){
    User.get(searchid, function(err, user) {
        if (err) {
            console.log(err);
            return res.send('error');
        } else {
        //DO LOGIC
        }
    });
}

Basicaly your test look like :

var myCode = rewire("../lib/myCode.js");

...

var UserMock = {
    get: function (searchid, cb) {

        cb(new Error(), null);
    }
};
myCode.__set__("User", UserMock);

myCode.myFunctionCallingUserGet(function (err, data) {
    // Test that you send error.
});

Upvotes: 1

Related Questions