Mocha: Per-test coverage?

Created on 15 Dec 2020  路  8Comments  路  Source: mochajs/mocha

Is it possible to gather per-test coverage? Perhaps via a plugin?

Is there any way to get started with this, and is it even possible?

feature question

All 8 comments

Running a single test with coverage should give you that.

Since most coverage tools I have used hook into nodes require lifecycle to instrument the code and accumulate numbers over the entire process runtime, I don't think you have many other ways to go

@Munter the problem is that that is slow.

The reason I want to do this, is to be able to see what tests ran through a specific line of code, so that I can (from GIT change information) run only affected tests.

I want to make a Mocha plugin that does this.

I suppose Istanbul is being used to instrument the code and provide coverage?

And if so, could I somehow make a Mocha plugin that ran before and after each test, reading the coverage information and resetting it between runs?

Obviously this wouldn't work in parallel, but that's fine for me.

Mocha itself doesn't deal with code coverage, so the choice of coverage tool is yours. I use Istanbul myself.

I guess you could write a reporter that could output coverage per test if it was possible to access the coverage tool at runtime and have it dump a report of its current line statement counts and reset all its counters before proceeding. That would keep you in the same process and only run expensive instrumentation once. I'm not aware of any such runtime API's though, and all of this seems out of scope for Mocha itself as well

@Munter thank you for the clarification. Can you link to relevant parts of the documentation on how to make such a reporter? I haven't been able to find anything.

The easiest way to create a new reporter is probably to extend the base reporter and have a look at what some of the other reporters do with the events they receive: https://github.com/mochajs/mocha/blob/master/lib/reporters/spec.js

Thank you so much @Munter. One last thing before I close this issue.

  1. Do you have TypeScript typings for the reporters?
  2. And how do I extend the "base.js" reporter from the outside? What is the import path? const base = require('mocha/base')?
  1. We do not have typescript typings. But we have spent considerable time on JSDoc annotations, which I know vscode is pretty good at picking up on, so that might be of some help
  2. I think the import path would be require('mocha/lib/reporters/base'), since I don't recall us moving files around or aliasing themin any way

It seems fine to close.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertherber picture robertherber  路  3Comments

Swivelgames picture Swivelgames  路  3Comments

CADBOT picture CADBOT  路  3Comments

niftylettuce picture niftylettuce  路  3Comments

danielserrao picture danielserrao  路  3Comments