Search code examples
typescriptnext.jsjestjscode-coverageglob

Exclude file/path with square brackets from jest coverage


I want to exclude a file from test coverage by adding an entry to collectCoverageFrom for Jest which has square brackets in the file name. Jest

  collectCoverageFrom: [
    './src/**/*.{js,jsx,ts,tsx}',
    '!./src/some/path/to/[fileWithSquareBrackets].ts',
  ]

This does not prevent test coverage from being collected for this file, however.


Solution

  • You have to escape the square brackets, as they are special characters for glob patterns, which Jest uses. Either of the following work:

      collectCoverageFrom: [
        './src/**/*.{js,jsx,ts,tsx}',
        '!./src/some/path/to/[[]fileWithSquareBrackets[]].ts',
      ]
    
      collectCoverageFrom: [
        './src/**/*.{js,jsx,ts,tsx}',
        '!./src/some/path/to/\\[fileWithSquareBrackets\\].ts',
      ]
    

    I slightly prefer the latter, as it is actually escaping the bracket, rather than using the bracket to signify a glob character class containing a square bracket.