【问题标题】:No Test case found Jest没有找到测试用例 Jest
【发布时间】:2019-12-22 01:32:21
【问题描述】:

我在使用 lint-staged 插件时遇到了一个奇怪的问题。之前还好好的。

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

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

但是当我使用husky pre-commit 和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"
      ]
   }

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

【问题讨论】:

    标签: jestjs husky lint-staged


    【解决方案1】:

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

    你需要的是--findRelatedTests

    "lint-staged": {
      "*.js": [
        "prettier --write",
        "eslint --ext .js --fix",
        "jest --bail --findRelatedTests"
      ]
    }
    

    --findRelatedTests 将查找需要/导入作为参数传递的文件的测试文件(在 lint-staged 的​​情况下,是暂存区域中的文件)。你可以阅读更多关于它是如何工作的here

    来自documentation

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

    【讨论】:

    • --bail 如何解决这个问题?
    • --bail 只是我喜欢与 lint-staged 一起使用的一种便利。这使得 Jest 在一个失败的测试套件后立即停止,因此您不必等待所有测试运行才能获得反馈。实际上,解决您的问题的是 --findRelatedTests。我已经为答案添加了解释。
    • 很高兴为您提供帮助 =D @ViníciusPachecoVieira
    • @DanielSousa 如果我将jest --bail --findRelatedTests 放在 4 个命令列表的末尾会有什么影响吗?
    • @ypahalajani 实际上 lint-staged 现在为您运行“git add”,因此您不再需要它了。我已经更新了最后运行 jest 的示例。
    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2021-06-07
    • 2021-09-15
    • 2020-03-20
    相关资源
    最近更新 更多