0

I'm attempting to test some API routes and my code coverage is good, but I'm consistently missing the err branch. Below is an example of one of my API route controllers.

var index = function(req, res) {
  request({url: privateUrl + '/players/' + req.params.playerId + '/games',
    headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
    method: 'GET'}, function(err, response, body) {
      if (err) {
        logger.warn('Error while retrieving games for player %d.', req.params.playerId, err);
        return res.status(500).json({
          message: err.message ? err.message : 'Error while retrieving player games.'
        });
      } else {
        res.json(helpers.JSONparse(body).response);
      }
    });
};

How would I test the err case? What I'd ideally like to do is .set('err', true) and then test that the res.status and err.message are what I'd expect. Here's the spec where I test a successful response:

it('should return an object with player games', function(done) {
  request
    .get('/api/players/' + playerId + '/games')
    .set('Content-Type', 'application/json')
    .set('cookie', cookie)
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      expect(err).toBeNull(err ? err.message : null);
      expect(res.body.games).toBeDefined();
      done();
    });
});
MattDionis
  • 3,534
  • 10
  • 51
  • 105

2 Answers2

0

The easiest way is to throw an error in your REST call, just put "/player1/" instead of player, or intentionally bad data.

Organiccat
  • 5,633
  • 17
  • 57
  • 104
0

You could use a free HTTP mock service such as mockable.io. It's a great way of testing that an application can handle different types of responses, including errors. All that you change in your application code is the URL: you point the Ajax request, temporarily, to the URL of your mock API.

kieranpotts
  • 1,510
  • 11
  • 8