我正在开发后端 Typescript 项目,我正在尝试获取单元测试用例的覆盖率报告。 Jest 在终端和 html 报告中返回空的覆盖率报告,没有说明任何内容。我也尝试过使用
-- --coverage --watchAll=false
但它也返回空文档。
package.json
"scripts":{
"unit-test": "jest --config='./config/jest/jest_unit.config.js' --forceExit --detectOpenHandles",
}
jest_unit.config.js
/**
* @file Jest Unit Test Configuration File
*/
module.exports = {
roots: ['../../tests'],
testRegex: '.*_unit.test.(js|ts|tsx)?$',
globals: {
'ts-jest': {
tsConfig: 'tsconfig.json',
},
},
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
testEnvironment: 'node',
reporters: [
'default',
[
'../../node_modules/jest-html-reporter',
{
pageTitle: 'Unit Test Report',
outputPath: 'tests/reports/unit-test-report.html',
includeFailureMsg: true,
},
],
],
collectCoverage: true,
collectCoverageFrom: [
'../../api/**/*.ts'
],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../../coverage",
coveragePathIgnorePatterns: [
"<rootDir>/node_modules"
],
coverageReporters: [
"json",
"lcov",
"text"
],
coverageThreshold: {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
};
文件夹结构
|-- app
|-- controllers
|-- schemas
|-- config
|-- jest
|-- jest_unit.config.js
|-- package.json
|-- tests
|-- api
|-- modules
|-- m1
|-- controllers
|-- m1_controller_unit.test.ts
|-- m1_controller_integration.test.ts
|-- m2
|-- models
|-- m1_model_unit.test.ts
|-- m1_model_integration.test.ts
|-- m3
|-- schemas
|-- m1_schema_unit.test.ts
|-- m1_schema_integration.test.ts
Jest Coverage htm 和终端显示没有覆盖线
我可以通过将配置文件移至根目录来解决此问题。在这个配置中一切都很好。我不知道为什么笑话会这样。
更新结构
文件夹结构
|-- app
|-- controllers
|-- schemas
|-- jest_unit.config.js
|-- package.json
|-- tests
|-- api
|-- modules
|-- m1
|-- controllers
|-- m1_controller_unit.test.ts
|-- m1_controller_integration.test.ts
|-- m2
|-- models
|-- m1_model_unit.test.ts
|-- m1_model_integration.test.ts
|-- m3
|-- schemas
|-- m1_schema_unit.test.ts
|-- m1_schema_integration.test.ts
package.json
"scripts":{
"unit-test": "jest --config='./jest_unit.config.js' --forceExit --detectOpenHandles",
}
尝试按如下方式更改您的
collectCoverageFrom
:
collectCoverageFrom: [
'../../tests/**'
],
**
表示递归地包含所有文件。 详细信息位于https://jestjs.io/docs/en/configuration#collectcoveragefrom-array
我用这个就可以了
package.json
...
"scripts": {
...
"test": "jest --maxWorkers=1 --coverage"
...
jest.config.js
module.exports = {
verbose: true,
preset: 'ts-jest',
testEnvironment: 'node',
globals: {
'ts-jest': {
isolatedModules: true
}
},
testPathIgnorePatterns: ['.d.ts', '.js'],
collectCoverageFrom: [
'**/*.ts',
'!**/build/**',
'!**/node_modules/**',
'!**/vendor/**'
]
};
我也随机面临这个问题,我没有解决办法或不知道为什么,但清除缓存并再次运行它总是有效的:
jest --clearCache
jest --coverage
我相信这可能与 ts-jest 有关,而不是笑话本身。
确保您的coveragePathIgnorePatterns 没有包含应该覆盖的测试的目录。