没有找到测试用例 Jest

Car*_*los 4 jestjs husky lint-staged

我正面临一个奇怪的lint-staged插件问题。早些时候它工作正常。

所以问题是当我运行npm run test它时会生成覆盖率报告。

"test": "cross-env CI=true react-scripts test --coverage",

在此处输入图片说明

但是当我使用husky预提交运行相同的命令时,lint-staged它不起作用。当我检查控制台时,我发现它正在针对已修改的文件运行。

> portal@0.1.0 test /Users/carlos/Desktop/portal
> cross-env CI=true react-scripts test --coverage "/Users/carlos/Desktop/portal/src/container/Auth/Login.page.js"

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In /Users/carlos/Desktop/portal
44 files checked.
testMatch: /Users/carlos/Desktop/portal/src/**/__tests__/**/*.{js,jsx,ts,tsx}, /Users/carlos/Desktop/portal/src/**/*.{spec,test}.{js,jsx,ts,tsx} - 6 matches
testPathIgnorePatterns: /node_modules/ - 44 matches
testRegex:  - 0 matches
Pattern: /Users/carlos/Desktop/portal/src/container/Auth/Login.page.js - 0 matches
npm ERR! code ELIFECYCLE
npm ERR! errno 1
Run Code Online (Sandbox Code Playgroud)

有明显的区别

当我跑

npm run test 它运行

cross-env CI=true react-scripts test --coverage

npm run test被 husky 和 ​​lint-staged 调用时

它被称为 cross-env CI=true react-scripts test --coverage "/Users/carlos/Desktop/portal/src/container/Auth/Login.page.js"

之后附加了文件路径 --covrage

这是我的包 JSON 配置。

"jest": {
    "collectCoverageFrom": [
      "src/**/*.js"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 80,
        "functions": 80,
        "lines": 80,
        "statements": 80
      }
    }
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "husky": {
      "hooks": {
        "pre-commit": "lint-staged"
      }
    },
  "lint-staged": {
      "*.js": [
        "prettier --write",
        "eslint src/ --fix",
        "npm run test",
        "git add"
      ]
   }
Run Code Online (Sandbox Code Playgroud)

注意:当我使用 lint-staged 时,只有当我使用pre-commit:npm run test它工作正常时才会发生这种情况。

Dan*_*usa 5

Jest 试图在您的暂存区运行文件,这就是它附加一些文件路径的原因。

你需要的是--findRelatedTests

"lint-staged": {
  "*.js": [
    "prettier --write",
    "eslint --ext .js --fix",
    "jest --bail --findRelatedTests"
  ]
}
Run Code Online (Sandbox Code Playgroud)

--findRelatedTests将查找需要/导入作为参数传递的文件的测试文件(在 lint-staged 的​​情况下,您的暂存区中的文件)。您可以在此处阅读有关其工作原理的更多信息。

文档

查找并运行覆盖作为参数传入的以空格分隔的源文件列表的测试。对于预提交钩子集成以运行最少数量的必要测试很有用。可以与 --coverage 一起使用以包含源文件的测试覆盖率,不需要重复的 --collectCoverageFrom 参数。

  • --bail 只是一种便利,我喜欢与 lint-staged 一起使用。这使得 Jest 在一个失败的测试套件后立即停止,因此您不必等待所有测试运行后再获得反馈。实际上,解决你的问题的是--findRelatedTests。我在答案中添加了解释。 (2认同)