React Native + Jest EMFILE:打开文件太多错误

IT技术 reactjs react-native jestjs ulimit
2021-05-26 13:29:22

我正在尝试运行 Jest 测试,但出现以下错误:

读取文件时出错:/Users/mike/dev/react/TestTest/node_modules/react-native/node_modules/yeoman-environment/node_modules/globby/node_modules/glob/node_modules/path-is-absolute/package.json /Users/mike/dev/react/TestTest/node_modules/jest-cli/node_modules/node-haste/lib/loader/ResourceLoader.js : 88 throw err; ^

错误:EMFILE:打开的文件太多,打开'/Users/mike/dev/react/TestTest/node_modules/react-native/node_modules/yeoman-environment/node_modules/globby/node_modules/glob/node_modules/path-is-absolute/ package.json' 在错误(本机)npm ERR!测试失败。有关更多详细信息,请参见上文。

令我感兴趣的是,错误中列出的路径指向 node_modules 目录中的一个文件,由于 testPathIgnorePatterns 中的 node_modules 条目,我预计该文件不会被读取。

我正在运行 Node 4.2.1,我安装的 React-Native 才一周,我今天安装了 Jest(所以我想我是最新的)。我在 Mac 上。

我已经运行:sudo ulimit -n 10240,关闭了所有终端窗口,甚至尝试重新启动。(在我之前添加的 .bash_profile 中ulimit -n 1024。我尝试了更大的数字。

为了确保问题不仅仅出现在我自己的项目中,我创建了一个新项目,react-native init TestTest并对 package.json 进行了 RN 的建议更改:

{
  "name": "TestTest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node_modules/react-native/packager/packager.sh",
    "test": "jest"
  },
  "dependencies": {
    "react-native": "^0.14.1"
  },
  "jest": {
    "scriptPreprocessor": "node_modules/react-native/jestSupport/scriptPreprocess.js",
    "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "promise",
      "source-map"
    ]
  },
  "devDependencies": {
    "jest-cli": "^0.7.1"
  }
}

但我每次都遇到同样的错误。

4个回答

我在一个小型 vuejs 项目中遇到了同样的问题。在我的情况下,修复只是一个小的配置属性:我把它放在我的jest.config.js

  watchPathIgnorePatterns: ['node_modules'],

对于任何与 vuejs 有相同问题的人。这是我的完整jest.config.js文件:

module.exports = {
  preset: '@vue/cli-plugin-unit-jest',
  transformIgnorePatterns: ['/node_modules/(?!(leaflet))'],
  watchPathIgnorePatterns: ['node_modules'],
  testMatch: [
    '<rootDir>/src/**/*.spec.js'
  ],
};

简短回答:将 'ulimit -n 4096' 添加到 ~.bash_profile 并打开一个新的终端窗口解决了我的问题。

答案与我没有正确设置 ulimit 有关。

sudo ulimit -n 10240

在我的 Mac 上默默地不会改变 ulimit。我最初认为它没有做任何事情,因为 10240 不是 1024 的增量。但是当我尝试 2048、4096 等时它也没有做任何事情。

那么,什么是“解决方案”?

  • ulimit -n(没有数字)会告诉你当前的值是多少
  • 对我来说,sudo ulimit -n 2048在终端窗口中输入并没有改变 ulimit(无论我尝试过什么数字)
  • 将 'ulimit -n 4096' 添加到 ~.bash_profile 并打开一个新终端解决了问题

我在powershell中运行windows。还使用了 Git Bash 并遇到了类似的问题。我更新了我的 package.json 如下:

  "devDependencies": {
    "jest-cli": "^0.8.2",
  },
  "jest": {
    "testPathDirs": ["__tests__"],
    "testPathIgnorePatterns": [
      "/node_modules/"
    ]
  },
  "scripts": {
    "test": "jest"
  },

请注意,这"testPathDirs": ["__tests__"],是我放置所有测试的目录。

现在我可以npm test毫无问题地运行了。最终似乎 Jest 正在导航/node_modules/应该排除目录。

我遇到了这个问题并通过运行修复了它

brew upgrade watchman