getting nyc/istanbul coverage report to work with typescript
Asked Answered
P

3

13

I'm struggling to get proper coverage with nyc/istanbul for my typescript/mocha/gulp project. I've tried a number of approaches, some of them seem to be unable to use source maps and other fails due to ts-node/tsc errors. My current setup is:

nyc relevant config in package.json

"scripts": {
    "test:coverage": "nyc npm run test:unit",
    "test:unit": "gulp mocha"
}
"nyc": {
    "check-coverage": true,
    "all": true,
    "extension": [
      ".js",
      ".jsx",
      ".ts",
      ".tsx"
    ],
    "include": [
      "src/**/!(*.test.*).[tj]s?(x)"
    ],
    "reporter": [
      "html",
      "lcov",
      "text",
      "text-summary"
    ],
    "report-dir": "docs/reports/coverage"
  }

gulpfile.js mocha relevant part

const SRC_DIR = path.join(__dirname, 'src');
const SRC_FILES = path.join(SRC_DIR, '**', '*.[jt]s?(x)');
const TEST_FILES = path.join(SRC_DIR, '**', '*.test.[jt]s?(x)');
const MOCHA_CONFIG = {
    src: [
        TEST_FILES
    ],
    watchSrc: [
        SRC_FILES,
        TEST_FILES
    ],
    mocha: {
        // compilers: [
        //     'ts:ts-node/register',
        //     'tsx:ts-node/register'
        // ],
        require: [
            './tests/setup.js',
            'ignore-styles',
            'source-map-support/register'
        ]
    }
};
gulp.task('mocha', mocha(MOCHA_CONFIG));

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./",
    "rootDir": "./src",
    "outDir": "./build",
    "allowJs": true,
    "module": "commonjs",
    "target": "es5",
    "lib": ["es5", "es6", "dom"],
    "sourceMap": true,
    "inlineSourceMap": false,
    "inlineSources": false,
    "experimentalDecorators": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "jsx": "react",
    "moduleResolution": "node"
  },
  "exclude": [
    "docs",
    "tests",
    "**/*.test.js",
    "**/*.test.jsx",
    "**/*.test.ts",
    "**/*.test.tsx",
    "tools",
    "gulpfile.js",
    "node_modules",
    "build",
    "typings/main",
    "typings/main.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useCache": true,
    "useBabel": true
  }
}

With the above setup coverage produces results for all the files but they are incorrect for TS files most probably due to source maps not being used (i.e. report shows no coverage for lines which are comments and the numbers seems to be wrong as well).

With a number of variant approaches tried with no success one of the most commonly suggested is to add "require": ["ts-node/register"] to nyc configuration yet then I'm getting errors complaining about i.e. gulpfile.js, docs/reports/coverage/lcov-report/prettify.js and number of other JS files to be not under 'rootDir' which is correct yet it is not clear why ts-node tries to process all the files out of src even if they are excluded in tsconfig.json (still the configuration gets really complex).

I'll appreciate any suggestion which way to go to get proper coverage report for TS files.

Permute answered 22/6, 2017 at 14:14 Comment(6)
Setting up correct testing with coverage can sometimes be cumbersome. I stopped using Mocha/Istanbul for React-Typescript projects and switched to Jest and ts-jest (github.com/kulshekhar/ts-jest), which comes with Istanbul required and all the goodies needed for React tests. This is for me a stable stack across different versions.Selassie
Thanks from suggestion! While actually this is one of my considerations, am I right it may require rewrite as jest differs from mocha?Permute
Mocha tests are easily rewritten into jest. Remove describe sections and change it() to test(). The assertions are also different. But the before* and after* sections are the same. Takes some time, but nog long...Selassie
and how it fits (or compare vs mocha/sinon/chai) to write tests for non react stuff?Permute
It's as easy as mocha!Selassie
Unfortunately we're using some libraries like proxyquire requireing additional attention. While it's doable still too much effort for simple switch. Still thanks for convicing me to give it a tryPermute
P
9

Recently I found a satisfiable solution by using "target": "es6" instead of es5 in tsconfig.json's compilerOptions. While changing target directly in tsconfig.json may not be an option as it affects build, the other tip is to use TS_NODE_COMPILER_OPTIONS='{"target":"es6"} which can be added directly in package.json scripts as i.e. :

"test:coverage": "TS_NODE_COMPILER_OPTIONS='{\"target\":\"es6\"}' nyc npm run test:unit",

where test:unit is whatever way being used to run actual tests (in my case just gulp mocha.

NOTE: I've also updated nyc to latest 11.1.0 and ts-node to 3.3.0 as suggested on https://github.com/istanbuljs/nyc/issues/618 thread

Permute answered 2/8, 2017 at 14:38 Comment(1)
This method fixed my issue when I got the "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option" errorRabbitry
D
2

I'm not sure this is the same problem but I'll put this here in case it helps future developers...

I wasn't getting any coverage data until I added exclude-after-remap=false to the nyc section of my package.json.

This is listed in the documentation but not in a very prominent way (IMO).

Daffi answered 13/5, 2019 at 13:59 Comment(0)
D
1

Since a lot of changes broke old working setups I created a verbose example project covering typescript + mocha + nyc supporting proper coverage also for non called files (this is often not included in examples) as well as some unit test examples and quality checks using latest versions.

I had several issues whilst going to mocha 8+ nyc 15+. Maybe it also helps someone else stumbling across it.

https://github.com/Flowkap/typescript-node-template

If you're only interested in coverage check the .ncyrc.yml and mocharc.yml as well as the call config in package.json. VsCode launch configs also included:

.nycrc.yml

extends: "@istanbuljs/nyc-config-typescript"

reporter:
  - html
  - lcovonly
  - clover
  # those 2 are for commandline outputs
  - text
  - text-summary
report-dir: coverage

.mocharc.yml

require:
  - ts-node/register
  - source-map-support/register
recursive: true
color: true
exit: true
extension:
  - ts
  - test.ts

test job in package.json

"test": "npm run lint && nyc mocha src test",
Decorticate answered 13/11, 2020 at 23:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.