Search code examples
typescriptistanbulnyc

How can I exclude private constructors which is written in TypeScript from function coverage using nyc?


I want to exclude private constructor from function coverage.
Actually I prefer to use private constructor in Factory Pattern.

Sample Code

class Instance { }
class InstanceA extends Instance { 
  public constructor() { super(); }
}
class InstanceB extends Instance { 
  public constructor() { super(); }
}
class InstanceC extends Instance { 
  public constructor() { super(); }
}

class Factory {
  private constructor() {
    /* I want to exclude this constructor */
  }

  public static createInstance(option: number): Instance {
    switch(option) {
      case 1:
        return new InstanceA();
      case 2:
        return new InstanceB();
      case 3:
        return new InstanceC();
      default:
        return undefined;
    }
  }
}


class ClientCode {
  private name: string;
  private age: number;
  private myInstance: Instance;

  public constructor(name: string, age: number, option: number) {
    this.name = name;
    this.age = age;
    this.myInstance = Factory.createInstance(option);
  }

  public foo(): void {
    /* do something */
  }
}

nyc options

  "nyc": {
    "cache": false,
    "extension": [
      ".ts",
      ".tsx"
    ],
    "include": [
      "script/**/*.ts"
    ],
    "exclude": [
      "**/*.d.ts",
      "script/entries/",
      "**/GlobalEnums.ts"
    ],
    "require": [
      "ts-node/register/transpile-only",
      "source-map-support/register"
    ],
    "reporter": [
      "html",
      "text",
      "text-summary"
    ],
    "temp-dir": "./coverage/.nyc_output"
  }

As I mentioned in comment, I want to exclude private constructor.
This makes my coverage percentage lower.

How can I exclude this?


Solution

  • Since nyc is just a CLI wrapper around istanbul you should be able to use its special comments to disable it:

    class Factory {
      /* istanbul ignore next */
      private constructor() {
        /* I want to exclude this constructor */
      }