0

Trying to figure out why I get no coverage out of nyc whatsovever, I ended up with a file single file ./x.js that only contains

#!/usr/bin/env node
'use strict'
console.log('======= starting tests =======');

In package.json I have

  ...
  "scripts": {
    "test": "nyc ./x.js",
  }
  ...

and when I run npm run test I get the following

  • console log from the one-liner
  • a html coverage report as requested in the config (see below), yet the line is not market as covered
  • despite configuring a cache directory, it stays empty which seems to indicate that on-the-fly instrumentation is not done.

From all the examples on net I assumed that instrumentation is done on the fly and that nyc instrument is rather for special uses cases. Can anyone provide some inside what is going on and what not? Here is (one of the gazillion versions of) the config I tried:

{
  "cache": true,
  "cache-dir": "./kkk",
  "instrument": true,
  "extension": [
    ".ts",
    ".js"
  ],
  "include": [
    "**/x.js"
  ],
  "reporter": [
      "html"
  ],
  "all": true
}

I start getting coverage output when not using "type": "module" in my package.json.

Versions:

  • node: v16.13.2
  • nyc: 15.1.0
Harald
  • 4,575
  • 5
  • 33
  • 72

1 Answers1

0

The problem seems to be that nyc in fact cannot load es-modules (ESM) on the fly. A possible solution could have been

npm i -D @istanbuljs/esm-loader-hook
NODE_OPTIONS='--experimental-loader @istanbuljs/esm-loader-hook' ./node_modules/.bin/nyc ..more options.. ./x.js

according to this github repository. Yet, this did not work for me, likely because my node version (16.13.2) is too new, as promised on that site.

The above link further points to c8 as a solution. Some background can be found on the c8 developer's blog. Bottom line: es-modules were difficult to implement for istanbul, so use a new node feature to collect coverage data and "just" convert this to human readable form: c8.

Works for me, given the example file in the question,

./node_modules/.bin/c8 node ./x.js

produces the expected coverage output. Further I noticed that when a .js file is included that was produced by the typescript compiler with "sourceMap": true, the coverage nicely shows the .ts file.

Harald
  • 4,575
  • 5
  • 33
  • 72