How can I exclude files from Jest watch?
Asked Answered
E

14

174

I'm doing some slightly bizarre stuff using Jest for testing where I'm writing some stuff to disk. If I use the watch flag in Jest however then I'm finding (quite obviously) that each time I write something to disk the tests refire again.

I don't currently have any sort of configuration, and I've taken a look at the documentation, but it's really not clear to me which option I need to be using to suppress watching particular files. I believe I can see options to exclude code from code-coverage and test execution, but not the actual watcher.

In my case I've got a setup like this and I just want to suppress my results directory:

  • __tests__
  • __snapshots__ (created by Jest)
  • results (created by me and the directory to exclude)
  • testfile1.js

How can I do this?

Ellyellyn answered 8/11, 2016 at 12:8 Comment(0)
C
239

From the documentation you need to add modulePathIgnorePatterns which is an array of string values which will be matched against

modulePathIgnorePatterns [array<string>] #

(default: []) An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be require()-able in the test environment. These pattern strings match against the full path. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ['<rootDir>/build/'].

https://facebook.github.io/jest/docs/configuration.html#modulepathignorepatterns-array-string

Add this to your configuration...

modulePathIgnorePatterns: ["directoryNameToIgnore"]

or:

modulePathIgnorePatterns: ["<rootDir>/dist/"]
Catheterize answered 8/11, 2016 at 12:13 Comment(7)
I've given this a try with "jest": { "modulePathIgnorePatterns": ["__tests__/results/"] }, but it doesn't work unfortunately.Ellyellyn
can you try shortening it? "jest": { "modulePathIgnorePatterns": ["tests"] },Catheterize
__tests__ is the default directory that jest uses to load its tests from. So it'd be awkward to rename, I could move my results directory up outside of __tests__ but I'm reluctant to do so unless I can't find an alternative.Ellyellyn
yes you're probably right, I'm just wondering if the pathName is somehow choking due to the slashes. In most cases when I'm using exclude directories in webpack I don't include the forward slashes and just the names of the directories like "node_module" etc...Catheterize
true. I've just tried moving the directory up, didn't seem to make any difference. I have worked out it's specifically a JSON file within there that I'm modifying that's causing the problem. Trying to just exclude that still doesn't seem to do much though :(Ellyellyn
In what file? package.json? Can you add it to your answer?Expressive
I just want to make sure: Does Jest automatically ignore checking the node_modules directory? (Most probably it must be the case!)Kaciekacy
M
89

To exclude a directory from Jest testing, use testPathIgnorePatterns

testPathIgnorePatterns

"testPathIgnorePatterns": ["directory to ignore"]

Below in file package.json, I have configured to ignore the "src" directory

{
      "name": "learn-test",
      "jest": {
        "testPathIgnorePatterns": ["src"]
      },
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "react": "^16.4.1",
        "react-dom": "^16.4.1",
        "react-scripts": "1.1.4"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "jest --watch",
        "eject": "react-scripts eject",

      },

      "devDependencies": {}
    }
Moorhead answered 12/7, 2018 at 18:45 Comment(8)
"testPathIgnorePatterns": ["<rootDir>/cypress/"] see here: github.com/wallabyjs/public/issues/2245Bivens
Best answer after 10 mins of searching.Chickweed
What's the difference with modulePathIgnorePatterns ?Neo
This one worked for me unlike modulePathIgnorePatternsScirrhous
Thanks I couldn't get testPathIgnorePatterns to do anything.Adriel
best answer after after 2 mins of searchingSchumann
This is the answer I was looking for.modulePathIgnorePatterns is not for excluding tests, it's for excluding other libs from being required during the test runners setup process. Just FYI for those looking to excluded tests in a build directory from running for exampleMablemabry
how to allow few in these ignored folders to run?Selfmortification
U
19

I had the same problem when I had a directory that must not be tested, although I still wanted it to be inside of the __tests__ directory (e.g., __mocks__).

You should not use a use relative paths in such case (no slashes). So inside of your package.json file add:

jest: {
  "modulePathIgnorePatterns": ["__mocks__"]
}

That solved my problem.

Undecagon answered 10/1, 2019 at 6:46 Comment(2)
Best answer so far... BUT, create-react-app and derived boilerplates won't support that option. I used watchPathIgnorePatterns instead. Just put it in your package.json's jest prop: "jest": {"watchPathIgnorePatterns":["__mocks__"]}Johnnyjohnnycake
This one worked for me when I nested __components__ folder inside __tests__.Hunley
B
13

Based on Jest documentation, watchPathIgnorePatterns should be the way you want to go. That works in Jest 23.x.x and later.

You can add this config to jest.config.js or package.json > jest

Boylston answered 18/10, 2018 at 16:30 Comment(1)
helped with me with vs-code tests doing all sorts of magic and failing. Also had to change "jest.jestCommandLine": "npm run test:jest --" in the vs code extension optionsGeddes
P
9

jest version: 27.2.1

In order to exclude from test and coverage:

"testPathIgnorePatterns" : [
  "tests/login/default/MockStrategy.js",
],
coveragePathIgnorePatterns: [
  "tests/login/default/MockStrategy.js"
],
Polygamous answered 25/10, 2021 at 23:2 Comment(0)
S
7

I use the following pattern and it works for me:

collectCoverageFrom: [
    'src/**/*.js',
    '!src/api/graphql/**/*.js',
    '!src/action/**/*.js',
    '!src/utils/dev/*.js',
    '!src/**/*.e2e.js',
],

! means we exclude the folder or file.

Spelter answered 11/10, 2020 at 10:12 Comment(3)
In what file? package.json? Can you add it to your answer?Expressive
within jest.config.js fileErlina
You can add it to package.json as well, - just add jest object like this - "jest": { rules goes inside}Overcritical
C
6

To exclude an entire folder, add the following in the "jest" property of the package.json file:

"modulePathIgnorePatterns": [
  "<rootDir>/src/services"
],

To exclude an individual file:

"collectCoverageFrom": [
  "!src/index.js"
],
Cathycathyleen answered 21/7, 2020 at 2:9 Comment(1)
Thanks, Working Added regular expression sample "collectCoverageFrom": [ "src/**/*.{ts,js}", "!src/db_access/*.{ts,js}", "!src/**/__fixtures/.{ts,js,json}", "!src/**/__removed__/.{ts,js,json}", "!src/models/.{ts,js,json}" ]Helio
I
4

In most of cases you will get the error: Your test suite must contain at least one test.

To ignore/exclude file or folders from the test, please modify the package.json

If the block "jest" does not exist add it like that:

...
"jest": {
    "collectCoverage": true,
    "testPathIgnorePatterns" : [
      "__tests__/properties.js",
      "__tests__/properties.js.sample"
    ]
},
...
Implead answered 11/6, 2021 at 15:59 Comment(1)
It actually works quite well. I prefer this cause I dont need to add folders. One thing I notice you have to restart the 'watch' for it to take effect.Plenary
I
3

I was looking for the command-line way of doing this without editing the config file everytime I try changing things.

This following runs jest in watch mode but excludes end-to-end test folders, independent from npm. you may have it in scripts section but if you do so then do not forget to remove "npx".

npx jest --watchAll --testPathIgnorePatterns "e2e_a/" "e2e_b/"

PS: some tests, especially E2E ones, may need to be run sequentially with -i, --runInBand flag. This comes in useful to exclude them from watch mode provided that they have their own folders. So prefer to have them in separate folders.

Implicit answered 3/10, 2022 at 20:41 Comment(0)
P
2

here are my 2 cents on this, as I feel there is some confusion in above answers:

Following is the jest segment in package.json file :

"jest": {
"testPathIgnorePatterns": ["wallet-svc/src/db/"],
"coveragePathIgnorePatterns": ["wallet-svc/src/db/"],
"modulePathIgnorePatterns": ["wallet-svc/src/db/"],
"moduleFileExtensions": [
  "js",
  "json",
  "ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
  "^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
  "**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}

If you notice I have mentioned 3 ignores - "testPathIgnorePatterns", "coveragePathIgnorePatterns" and "modulePathIgnorePatterns". It so happens at time when you are running tests, the files are ignored but when you run the coverage, jest does not ignore those file and you see them in the coverage report. Better to include all 3 tags.

I found this thread helpful : https://github.com/facebook/jest/issues/1815#issuecomment-684882428

Pinkiepinkish answered 13/9, 2021 at 14:44 Comment(0)
B
1

I had a similar situation, and adding testRegex in the jest.config.js was the complete solution for me, which specify which files exactly to be tested!

testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$'
Beeswax answered 24/8, 2022 at 13:45 Comment(0)
S
0

Skipping files in the test cases report collection is possible using "collectCoverageFrom" in the latest version of create-react-app, jest:

"jest": {
    "collectCoverageFrom": [
        "src/**/*.{js,jsx,ts,tsx}",
        "!<rootDir>/src/registerServiceWorker.js",
        "!<rootDir>/src/serviceWorker.js",
        "!<rootDir>/node_modules/"
    ]
},
Successor answered 4/8, 2020 at 10:22 Comment(2)
In what file? What is the name of the file?Expressive
Missing: Note: This option requires collectCoverage to be set to true or Jest to be invoked with --coverage.Theodore
A
0

I used this config in my package.json to exclude index.js and reportWebVitals.js files from coverage report.

  "jest": {
    "collectCoverageFrom": [
      "!<rootDir>/src/reportWebVitals.js",
      "!<rootDir>/src/index.js"
    ],
  }
Asco answered 15/6, 2021 at 5:27 Comment(0)
A
0

To ignore entire file Put /* istanbul ignore file */ at the top of the page

/* istanbul ignore file */
import { useState } from "react";
import ReactDOM from "react-dom/client";

const FavoriteColor = () => {
const [color, setColor] = useState("red");

 return (
   <>
    <h1>My favorite color is {color}!</h1>
   </>
 )
}
Airship answered 19/1 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.