2

I'm new to unit testing. I'm working in Node.js and I'm using the async module. Here's the code I'm working with:

module.exports = {
    postYelp: function (cb, results) {
        if (results.findLocation) {
            results.client.post(['resources', 'Yelp'].join('/'), results.findLocation, function (err, data, ctx) {
                /* istanbul ignore next  */
                if (err) {
                    cb(err);
                } else {
                    console.log('data', data);
                    console.log('ctx', ctx.statusCode);
                    return cb(null, ctx.statusCode);
                }
            });
        }
        /* istanbul ignore next  */
        else cb(null);
    },
}

So as you can see, the the 3rd argument in the function call to results.client.post is an anonymous callback.

I want test coverage for this callback. If I could easily refactor to create a named function with the same code as the callback and replace it, I could test it separately. However, the enclosing function ("postYelp") has its own callback ("cb") that must be used inside the anonymous callback function.

How can I unit test this anonymous function code?

1 Answer 1

1

OK I figured it out. I didn't have to refactor, just had to find a way to pass arguments to the anonymous callback. Here's the code:

    describe('when postYelp method is called', function() {
    it('should call the post method', function() {
        var cbspy = sinon.spy(cb);
        var post = sinon.stub(client, 'post');
        var results = {};
        results.client = {};
        results.client.post = post;
        results.findLocation = {'id': 'lyfe-kitchen-palo-alto'};
        post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201});
        helpers.postYelp(cbspy, results);
        assert(cbspy.called);
        client.post.restore();
    });
});

Basically I used sinon to create a stub of the inner function (client.post). I required the client and the OUTER function in my test file. This line allows me to feed the right parameters to the inner function:

post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201});

"2" means the anonymous callback is the 3rd argument in the function call for the post method. "null" is the "err" argument, and the objects "{'statusCode': 201}" really could have been any value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.