istanbuljs / nyc

the Istanbul command line interface
https://istanbul.js.org/
ISC License
5.54k stars 353 forks source link

nyc mocha is showing unknown(0%) code coverage with typescript module. #1528

Open RajMarutitech opened 10 months ago

RajMarutitech commented 10 months ago

I have all the files are with .ts extension. My package.json file looks like

  "name": "temp-node",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/src/index.js",
    "test": "nyc mocha --require ts-node/register dist/test-test/add.test.js"

  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^20.5.7",
    "chai": "^4.3.8",
    "mocha": "^10.2.0",
    "nyc": "^15.1.0",
    "sinon": "^15.2.0",
    "ts-node": "^10.9.1",
    "typescript": "^5.2.2"
  },
  "nyc": {
    "extends": "@istanbuljs/nyc-config-typescript",
    "check-coverage": true,
    "all": true,
    "include": [
        "src-test/**/*.ts"
    ],
    "exclude": [
        "test-test/**/*.ts"
    ],
    "reporter": [
        "html",
        "lcov",
        "text",
        "text-summary"
    ],
    "report-dir": "coverage"
  }
}

And the tsconfig file is:

{
    "compilerOptions": {
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        "esModuleInterop": true,
        "target": "ESNext",
        "sourceMap": true,
        "outDir": "dist",
        "rootDirs": ["src-test", "test-test"],
        "baseUrl": "src-test",
        "paths": {
            "*": ["src-test/*"]
        }
    },
    "include": [
        "src-test/**/*",
        "test-test/*"
    ],
    "exclude": [
        "node_modules",
        "dist"
    ]
}

Test file looks like:

// test/test_math.js
import { add, subtract } from '../src-test/math.js'
import { multiply, divide } from '../src-test/utils/util.js'
import { expect } from 'chai';
import { describe, it } from 'node:test';

describe('Math operations', () => {
  it('should add two numbers', () => {
    expect(add(2, 3)).to.equal(5);
  });

  it('should subtract two numbers', () => {
    expect(subtract(5, 3)).to.equal(2);
  });

  it('should multiply two numbers', () => {
    expect(multiply(2, 3)).to.equal(6);
  });

  it('should divide two numbers', () => {
    expect(divide(6, 3)).to.equal(2);
  });
});

Now when I run npm test, it is showing output as

Statements   : 0% ( 0/8 )
Branches     : 100% ( 0/0 )
Functions    : 0% ( 0/4 )
Lines        : 0% ( 0/8 )

I think I might misconfigured the tsconfig or it is the issue with NYC that it is not working like this with typescript and any other configuration is needed to run NYC and get the code coverage of the typescript code.

One try was successful: