-- --coverage
参数无法运行,并且应该使用下面的一个命令将CI
设置为true
。
默认情况下,npm test使用交互式CLI运行监视器。但是,您可以通过设置名为CI的环境变量来强制运行测试一次并完成进程。
set CI=true && npm test
set CI=true && npm run build
($env:CI = "true") -and (npm test)
($env:CI = "true") -and (npm run build)
CI=true npm test
CI=true npm run build
文档中不包含此部分内容
docker run -e CI=true [myImage] npm run test
在Jest的观察模式下,覆盖率无法工作。
因为默认情况下,“react-scripts test --env=jsdom”在观察模式下运行,必须关闭观察模式才能生成覆盖输出。
以下摘自package.json的内容展示了一行“coverage”,说明如何在使用create-react-app引导的应用程序中实现代码覆盖率。
这只是修改后的“test”脚本,其中组合添加了选项--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"
}
请注意,使用独立的双破折号--已经过时。大多数情况下,出现此问题的原因如下。
Not mentioning the required npm-script
arguments in the
package.json
file. If you use create-react-app
to create your
react application, then it will not accept any command line
arguments. To resolve this problem, add following line under the
script
tag in your package.json
.
"test": "react-scripts test --coverage --watchAll", //mark --watchAll=false if you want.
Not mentioning the required jest
configuration arguments in
the package.json
or jest.config.js
files. You should mention the files
which needed to include in your test coverage under the jest
configurations. Add following configurations in your
package.json
.
package.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"
]
},
在我的情况下,指定一个目录是有效的。
"test:cover": "react-scripts test --coverage src"
"test:ci": "cross-env CI=true react-scripts test --forceExit --detectOpenHandles",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"test:coverage": "react-scripts test --coverage",
"eject": "react-scripts eject"
},
"scripts": {
//* other scripts like start, build
"test": "react-scripts test",
"test:coverage": "react-scripts test --coverage --watchAll=false",
},
奖励分: 由于运行覆盖测试需要时间来生成覆盖范围,因此我们可以添加两个脚本,一个用于普通测试以了解测试是否通过,另一个用于生成覆盖率。
现在您可以根据用例运行测试或带有覆盖范围的测试:
npm run test
npm run test:coverage