..

"Error: ENOSPC: System limit for number of file watchers reached" during react-scripts test

Recently when running unit tests for a react app on Linux, I came across the following error:

internal/fs/watchers.js:173
    throw error;
    ^

Error: ENOSPC: System limit for number of file watchers reached, watch '/home/wbruschi/dev/mhl/web/react-app/node_modules/eslint-plugin-react/lib'
    at FSWatcher.start (internal/fs/watchers.js:165:26)
    at Object.watch (fs.js:1274:11)
    at NodeWatcher.watchdir (/home/wbruschi/dev/mhl/web/react-app/node_modules/sane/src/node_watcher.js:175:20)
    at Walker.<anonymous> (/home/wbruschi/dev/mhl/web/react-app/node_modules/sane/src/common.js:116:12)
    at Walker.emit (events.js:197:13)
    at /home/wbruschi/dev/mhl/web/react-app/node_modules/walker/lib/walker.js:69:16
    at go$readdir$cb (/home/wbruschi/dev/mhl/web/react-app/node_modules/graceful-fs/graceful-fs.js:162:14)
    at FSReqCallback.args [as oncomplete] (fs.js:145:20)

By default react-scripts run jest using the –watch flag. Unfortunately the version of react-scripts that I have does not ignore the node_modules directory, which causes this error because the OS has a configurable limit on the number of files it can watch.

Some posted solutions suggest increase this limit. I think it’s better to setup jest to ignore the node_modules directory. To do so, add this option to your package.json file:

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

If you run “npm test” now, you will see the following error:

Out of the box, Create React App only supports overriding these Jest options:

  • collectCoverageFrom
  • coverageReporters
  • coverageThreshold
  • globalSetup
  • globalTeardown
  • resetMocks
  • resetModules
  • snapshotSerializers
  • watchPathIgnorePatterns.

These options in your package.json Jest configuration are not currently supported by Create React App:

  • modulePathIgnorePatterns

If you wish to override other Jest options, you need to eject from the default setup. You can do so by running npm run eject but remember that this is a one-way operation. You may also file an issue with Create React App to discuss supporting more options out of the box.

npm ERR! Test failed.  See above for more details.

To workaround, edit node_modules/react-scripts/scripts/utils/createJestConfig.js and add “modulePathIgnorePatterns” to the “supportedKeys” array.