Search code examples
javascriptunit-testingmocha.jsistanbulnyc

How to test async calls so istanbul will cover it?


Im testing unit-testing my API. After i wrote all tests i implemented coverage tool istanbul. It covered everything without problems but branches. After looking at report i saw that async calls were not tested, but in reality they were run atleast 5 times. In this case async was run 15 times.

Small example of my test:

describe('GET /tables', () => {
  it('should GET tables', (done) => {
    chai.request(server)
      .get('/api/v1/tables')
      .then((res) => {
        expect(res).to.have.status(200);
        expect(res.body).to.be.a('array');
        done();
      })
      .catch((err) => {
        done(err)
      })
  });
})

Part of coverage report for that test:

export default async (req, res) => {
  let tables = [];
  try {
    tables = await Tables.findAndCountAll({
      where: {
        ...req.filter,
        material: null
      },
      // order: sort ? sort : [],
      limit: req.pagination.limit, 
      offset: req.pagination.offset
    });
  } catch (err) {
    console.log(err);
    return res.status(500).send({ error: 'Internal server error' });
  }

Line1: Marks async (r and says branch not covered


Solution

  • Fixed it. As i understand this problem, when nyc gets the coverage for the transpiled code it can't map it back to original source, so when that happens nyc drops coverage. Plugin babel-plugin-istanbul fixed that. It gives the support for ES2015+ code so its backward compatible using babel. I followed this simple tutorial.