How to create a workspace coverage report in nrwl/nx monorepo?

This is going to be a short one. I’m using nrwl/nx a LOT. I’m also testing a LOT. Lately I needed to add a coverage report to one of my nrwl/nx repositories. The coverage tool I was using needed the coverage in one file, while the nrwl/nx creates the reports per library and app.

So, a little bit of research showed me I could just concatenate the lcov.info files into one file and it’s going to do the trick.

I’ve written a small utility that does that for me:

const glob = require('glob');
const fs = require('fs');
const path = require('path');

const getLcovFiles = function (src) {
  return new Promise((resolve, reject) => {
    glob(`${src}/**/lcov.info`, (error, result) => {
      if (error) return reject(error);
      resolve(result);
    });
  })
};

(async function(){
  const files = await getLcovFiles('coverage');
  const mergedReport = files.reduce((mergedReport, currFile) => mergedReport += fs.readFileSync(currFile), '');
  await fs.writeFile(path.resolve('./coverage/lcov.info'), mergedReport, (err) => {
    if (err) throw err;
    console.log('The file has been saved!');
  });
})();

I put this file in the tools folder. You might also want to install the glob library:

yarn add -D glob

I’ve then created a test:ci npm command that runs the tests AND creates the coverage report:

"test:ci": "ng run-many --target=test --all --parallel --coverage --coverageReporters=lcov && node ./tools/coverageMerger.js",

this results in all the tests running (in parallel) and after they all finish, the script concatenates my coverage into a big lcov file.

Since I’m using github actions, all I needed to do was add this to my workflow after the tests:

      - name: Coveralls
        uses: coverallsapp/github-action@master
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

And that’s about it.

I hope this helps you in any way 🙂

Sign up to my newsletter to enjoy more content:

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mike Graham
Mike Graham
2 years ago

i documented a recipe for publishing coverage reports in nx / angular / jest to sonar
https://stackoverflow.com/a/70530811/7085047

Yonatan Kra
Admin
2 years ago
Reply to  Mike Graham

Thank you!

Robin
Robin
1 year ago

works as expected. Thank you very much!