lundi 29 janvier 2018

Testing MongoDB error path using Mocha

I am writing tests for a express route with MongoDB backend. Let's take a stub of the get functionality:

getAllResources() {
  return new Promise((resolve, reject) => {
    this.books.find({}).toArray()
      .then(docs => {
        resolve({
          status: 200,
          response: docs
        });
      })
      .catch(err => {
        reject({
          status: 500,
          data: 'Error'
        });
      })
  })
}

Now, I have a test like:

it('getAllResources should return empty array', async function() {
  let result = await sut.getAllResources();
  should.exist(result.status);
  should.exist(result.response);
  result.response.should.have.length(0);
});

But the scenario if the DB errors out is missed. Hence I am missing coverage on that segment. With all the routes I see a significant amount of coverage miss and want to improve it. I'm not sure how I can mock the Mongo functions.

I am currently using mongodb ^3.0.1, mocha ^5.0.0, chai ^4.1.2, sinon ^4.1.6, istanbul ^0.4.5. I am not using any in memory alternative for testing, but instead using collections with prefixes.

Aucun commentaire:

Enregistrer un commentaire