Jest的collectCoverageFrom和coverageThreshold无法正常工作

3

我有一个简单的创建React应用程序。因为我的项目是使用TypeScript编写的,所以我创建了jest.config.ts文件。

import type { Config } from "@jest/types";

// Sync object
const config: Config.InitialOptions = {
    collectCoverageFrom: ["./src/modules/*.tsx", "./src/hooks/*.tsx", "./src/components/*.tsx"],
    coverageThreshold: {
        global: {
            statements: 100,
            branches: 100,
            functions: 100,
            lines: 100,
        },
    },
};
export default config;

但是当我运行npm tnpm run test --watch时,我的配置文件中的coverageThresholdcollectCoverageFrom不起作用。我不知道出了什么问题。 之前我的配置文件扩展名为js,但我更改了它的类型,因为我认为这是它无法正常工作的原因。
我还尝试编写以下内容,而不是这个collectCoverageFrom: ["./src/modules/*.tsx", "./src/hooks/*.tsx", "./src/components/*.tsx"],

collectCoverageFrom: ["**/src/modules/*.tsx", "**/src/hooks/*.tsx", "**/src/components/*.tsx"],

和这个

collectCoverageFrom: ["**/src/**/*.tsx"],

但是jest.config文件不起作用。 package.json
{
    "name": "ui",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@emotion/react": "^11.5.0",
        "@testing-library/jest-dom": "^5.11.4",
        "@testing-library/react": "^11.1.0",
        "@types/node": "^12.0.0",
        "@types/react": "^17.0.34",
        "web-vitals": "^1.0.1"
        // other libs
    },
    "scripts": {
        "start": "react-scripts start",
        "proxy": "concurrently \"react-scripts start\" \"npm run mock\" ",
        "mock": "nodemon mock --watch mock",
        "build": "react-scripts build",
        "test": "react-scripts test --coverage",
        "eject": "react-scripts eject",
        "prettier": "prettier --ignore-path .gitignore --write \"**/*.+(js|json)\"",
        "lint": "eslint --ignore-path .gitignore --ext .js,.ts,.tsx .",
        "format": "npm run prettier -- --write",
        "check-format": "npm run prettier -- --list-different",
        "validate": "npm-run-all --parallel lint check-format build"
    },
    "devDependencies": {
        "@testing-library/react-hooks": "^7.0.2",
        "@types/jest": "^26.0.24",
        "ts-jest": "^27.1.4",
        // any other libs
    }
}

同时,coverage文件夹中的index.html文件显示覆盖率如下:

60.6% 语句 20/33 40% 分支 4/10 46.66% 函数 7/15 58.62% 17/29

这意味着当我运行npm t时,jest必须向我显示全局覆盖率未达到100%的错误。但是我在终端中没有看到任何错误。

1个回答

3

通过将Jest配置添加到我的package.json中,已解决此问题。

  "devDependencies": {
      "@testing-library/react-hooks": "^7.0.2",
      "@types/jest": "^26.0.24",
      "ts-jest": "^27.1.4",
      // any other libs
  },
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.tsx",
      "src/components/*.tsx",
      "!**/node_modules/**",
      "!**/src/test-utils/**",
      "!**/src/index.tsx"
    ],
    "coverageThreshold": {
        "global": {
            "statements": 100,
            "branches": 100,
            "functions": 100,
            "lines": 100
        }
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接