nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
106.53k stars 29.03k forks source link

Support statement coverage #54530

Open RedYetiDev opened 3 weeks ago

RedYetiDev commented 3 weeks ago

I think the Node.js coverage reporter should include support for reporting statement coverage.

My idea is to parse the source code into an Abstract Syntax Tree (AST) using acorn-walk, and then use the Statement callback to extract statements. They could then be converted to CoverageStatements, (similarly to how the getLines function works with lines to CoverageLines).

These statements could then be mapped to ranges in the same way that lines are handled in mapRangeToLines.

I saw a (extremely complicated) way of doing this in https://github.com/cenfun/monocart-coverage-reports/, so it appears to be possible.

cjihrig commented 2 weeks ago

I see at least two issues with doing this:

Of course there is some code complexity to doing this too. While I agree that statement coverage would be nice to have, I haven't seen any users of the test runner asking for it either. My understanding (which @molow seemed to confirm) is that C8 does not report this metric from V8 coverage. If they aren't doing it, I don't see a great reason for us to do it either.

cenfun commented 2 weeks ago

The latest version of C8 can do this with --experimental-monocart

c8 --experimental-monocart --reporter=v8 --reporter=console-details node foo.js

As an alternative, we can also use the custom test reporter

node --test-reporter=node-monocart-coverage --test tests

see node-monocart-coverage

Indeed, it is extremely complicated and hurt performance. There is a benchmark for reference, TypeScript is currently using c8 --experimental-monocart to generate coverage reports.

image

Check TypeScript coverage job in CI See https://github.com/microsoft/TypeScript/pull/58850

AriPerkkio commented 2 weeks ago

If this was implemented directly in V8, whole JS/Node ecosystem could benefit from this. Adding AST based coverage analysis is not ideal for performance.