npm test -- --coverage never exits

Anu*_*nup 6 continuous-integration frontend unit-testing node.js reactjs

I am using create-react-app to create a react application. When I executes npm test -- --coverage the test never exists. npm test actually runs react-scripts test. Any Idea?

在此处输入图片说明

Mat*_*san 28

-- --coverage部分将不起作用,应使用以下命令之一设置CItrue.

默认情况下,npm test 使用交互式 CLI 运行观察器。但是,您可以通过设置一个名为 CI 的环境变量来强制它运行一次测试并完成该过程。

来源:React 文档

Windows (cmd.exe)

  • set CI=true && npm test

  • set CI=true && npm run build

Windows (Powershell)

  • ($env:CI = "true") -and (npm test)

  • ($env:CI = "true") -and (npm run build)

Linux、macOS (Bash)

  • CI=true npm test

  • CI=true npm run build


未包含在文档中

对于 Docker(节点和反应):

docker run -e CI=true [myImage] npm run test


mic*_*mor 10

在观看模式下,Jest无法使用覆盖范围。

由于“ react-scripts test --env = jsdom”默认情况下在监视模式下工作,因此在生成coverage输出时必须关闭监视模式。

以下来自package.json的摘录包含一行“ coverage”用于说明,如何在由create-react-app引导的应用程序中实现代码覆盖率。

这只是修改后的“测试”脚本,其中选项--watchAll = false--coverage组合添加:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "coverage": "react-scripts test --env=jsdom --watchAll=false --coverage",
    "eject": "react-scripts eject"
  }
Run Code Online (Sandbox Code Playgroud)

请注意,使用独立的双破折号-已过时。


Ara*_*chi 5

大多数情况下,由于以下原因可能会出现此问题。

  1. 没有提及文件npm-script中所需的参数 package.json。如果您使用create-react-app它来创建 React 应用程序,那么它将不接受任何命令行参数。要解决此问题,请 scriptpackage.json.

    "test": "react-scripts test --coverage --watchAll", //mark --watchAll=false if you want.
    
    Run Code Online (Sandbox Code Playgroud)
  2. 没有提及或文件jest中所需的配置参数。您应该在笑话配置下提及需要包含在测试覆盖范围中的文件。在您的 .package.jsonjest.config.jspackage.json

包.json

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.js",
      "!src/index.js", // files you need to avoid in test coverage
      "!src/hooks/*.js",
      "!src/context/*.js"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 90,
        "lines": 90,
        "statements": 90
      }
    },
    "coverageReporters": [
      "html",
      "text"
    ]
  },
Run Code Online (Sandbox Code Playgroud)