Search code examples
jestjsnestjsts-jest

Why are my NestJS Guards not included in Jest code coverage?


I have written unit tests for my Nest Guards, and then run just fine and pass, but when I check my code coverage they are not included in that! You can see in my console output the *.guard.ts files are passing testing, and then not being listed in the coverage

Jest console output

This is what my jest.config.js looks like:

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');

/** @type {import('jest').Config} */
const config = {
  testEnvironment: 'node',
  resetMocks: true,
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: 'src',
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },

  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
    prefix: '<rootDir>/../',
  }),

  //Code Coverage
  collectCoverageFrom: ['<rootDir>/**/*.{js,jsx,ts,tsx}'],
  coverageDirectory: '../coverage',
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '.const.ts',
    '.d.ts',
    '.dto.ts',
    '.enum.ts',
    '.entity.ts',
    '.module.ts',
    '.schema.ts',
    '.strategy.ts',
    'swagger-setup.ts',
    'main.ts',
  ],
  coverageThreshold: {
    global: {
      branches: 100,
      functions: 100,
      lines: 100,
      statements: 100,
    },
  },
};

module.exports = config;

It seems pretty basic to me, I'm not excluding *.guard.ts files anywhere


Solution

  • Well I feel dumb. The problem here was my '.d.ts' pattern. I had assumed these were minmatch patterns, but they are regular expressions! So the . matched any character, meaning guard.ts would match the .d.ts pattern. ugh.

    So the fix was to escape the dots in all my exclusion pattnerns, like this:

    coveragePathIgnorePatterns: [
      '/node_modules/',
      '\\.const\\.ts',
      '\\.d\\.ts',
      '\\.dto\\.ts',
      '\\.enum\\.ts',
      '\\.entity\\.ts',
      '\\.module\\.ts',
      '\\.schema\\.ts',
      '\\.strategy\\.ts',
      'swagger-setup\\.ts',
      'main\\.ts',
    ],