简体   繁体   中英

How to force error branch in jasmine-node test

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?

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)
  // ...

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