How to force error branch in jasmine-node test
Asked Answered
T

1

10

I'm testing the controller logic behind API endpoints in my node server with jasmine-node. Here is what this controller logic typically looks like:

var getSummary = function(req, res) {
  var playerId = req.params.playerId;

  db.players.getAccountSummary(playerId, function(err, summary) {
    if (err) {
      logger.warn('Error while retrieving summary for player %d.', playerId, err);
      return res.status(500).json({
        message: err.message || 'Error while retrieving summary.',
        success: false
      });
    } else {
      res.json({success: true, summary: summary});
    }
  });
};

Below is how I successfully test the else block:

describe('GET /api/players/:playerId/summary', function() {
  it('should return an object summarizing the player account',   function(done) {
    request
      .get('/api/players/' + playerId + '/summary')
      .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.success).toBe(true);
        expect(res.body.summary).toBeDefined();
        done();
      });
  });
});

This works nicely, but leaves me with poor branch coverage as the if block is never tested. My question is, how do I force the error block to run in a test? Can I mock a response which is set to return an error so that I can test the correct warning is logged and correct data is passed back?

Trustless answered 1/10, 2016 at 17:59 Comment(1)
See Use Jasmine to stub JS callbacks based on argument values. The trick you're trying to do is create a Mock.Maroon
D
1

It depends on your tests. If you only want to unit test, spies are the way to go. You can just stub your db response. Be aware that in this case the database is not called though. It's just simulated.

const db = require('./yourDbModel');
spyOn(db.players, 'getAccountSummary').and.callFake(function(id, cb) {
  cb(new Error('database error');
});

request
  .get('/api/players/' + playerId + '/summary')
  .set('Content-Type', 'application/json')
  .set('cookie', cookie)
  .expect(500)
  // ...

If you want functional/integration tests, you need to call your request simply with wrong data, for example a players id that doesn't exist in your database.

request
  .get('/api/players/i_am_no_player/summary')
  .set('Content-Type', 'application/json')
  .set('cookie', cookie)
  .expect(500)
  // ...
Duet answered 10/10, 2016 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.