Search code examples
typescriptunit-testingmocha.jstypeormnyc

Istanbul code coverage shows branch not covered in constructor


I'm testing my nodejs written typescript with mocha and chai, for code coverage i'm using nyc.

as part of my project i'm also using Typeorm as ORM tool and using inversify as IoC container.

When writing unit test cases, code coverage says branch not covered at where ever is a decorator e.g. @Inject or @Response, etc., passed as a parameter either in constructor or to any method.

I'm suspecting

"experimentalDecorators": true,
"emitDecoratorMetadata": true,

is causing the issue, but I can't make them false which causes Typeorm to fail.

Code coverage report

Constructor issue Below is the tsconfig.json

  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "outDir": "dist",
    "noImplicitAny": true,
    "baseUrl": "./",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "types": [
      "node",
      "mocha"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "include": [
    "src/**/*.ts",
    "migrations/**/*.ts"
  ],
  "exclude": [
    "./node_modules",
    "./dist"
  ]
}

npm commands for test and test coverage

"test": "mocha -r ts-node/register ./tests/unit/**/*.ts --exit",
"test:cov": "rimraf reports && rimraf .nyc_output && nyc mocha

Solution

  • By adding the "@istanbuljs/nyc-config-typescript" into the .nycrc.json to extends array and "source-map-support/register" into the .mocharc.json to require array resolved the issue

    .nycrs.json

    
    {
        "extends" : [
            "@istanbuljs/nyc-config-typescript"
        ],
        "include": [
            "src"
        ],
        "extension": [
            ".ts"
        ],
        "check-coverage": true,
        "lines": 0,
        "reporter": [
            "lcov",
            "text-summary"
        ],
        "report-dir": "reports/coverage",
        "all": true,
        "exclude": [
            "./node_modules",
            "src/*.d.ts",
            "./dist",
            "./migrations",
            "./commitlint.config.js",
            "**/*.entity.ts",
            "**/I[A-Z]*.{ts}",
            "**/*.config.{ts}",
            "**/config.ts"
    
        ],
        "timeout": 4000
    }
    

    .mocharc.json

    {
        "extension": [
          ".ts"
        ],
        "recursive": true,
        "require": [
          "ts-node/register",
          "source-map-support/register"
        ],
        "exit": true,
        "spec": "./tests/unit/**/*.ts"
      }
    

    and running test coverage command

    nyc mocha