jestjs - 没有找到测试用例 Jest

标签 jestjs husky lint-staged

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

所以问题是当我运行 npm run test 时它生成覆盖率报告。
"test": "cross-env CI=true react-scripts test --coverage",
enter image description here

但是当我用 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

有明显的区别

当我跑
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"
      ]
   }

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

最佳答案

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

"lint-staged": {
  "*.js": [
    "prettier --write",
    "eslint --ext .js --fix",
    "jest --bail --findRelatedTests"
  ]
}
--findRelatedTests将查找需要/导入作为参数传递的文件的测试文件(在 lint-staged 的​​情况下,您的暂存区中的文件)。您可以阅读更多关于它是如何工作的 here .
来自 documentation :

Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.

关于jestjs - 没有找到测试用例 Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57512536/

相关文章:

node.js - 无法窥探原始值;在 nestJS 中给出未定义

javascript - 开 Jest - TypeError : Cannot read property 'fn' of undefined

node.js - 当我提交时如何获取 git commit 消息?

git - 为什么在取消 git 提交后我的更改消失了,我该如何恢复它们?

Husky/lint-staged 是否可以排除/忽略文件?

react-redux - 使用 scss 运行 React 单元测试

javascript - Jest 期望使用不包含特定字段的对象调用 mock

Husky Hook 不能与测试一起正常工作

git - 哈士奇的工作原理是什么?

javascript - 当我提交新文件时,husk 不执行预提交