jest-junit无法作为reporter使用,仅支持testResultsProcessor的问题排查
Jest使用reporter方式配置jest-junit报错的原因分析
问题背景
在CI环境中尝试按照jest-junit官方文档的方式执行测试命令:
jest --ci --reporters=default --reporters=jest-junit
或者带双引号的写法:
jest --reporters="default" --reporters="jest-junit"
无论哪种写法都会抛出错误,错误信息如下:
nps is executing `test.ci` : jest --ci --reporters=default --reporters=jest-junit **/*.test.[jt]s Error: Could not resolve a module for a custom reporter. Module name: tests/fail.test.ts at <project_root>/node_modules/jest-config/build/normalize.js:426:15 at Array.map (<anonymous>) at normalizeReporters (<project_root>/node_modules/jest-config/build/normalize.js:409:20) at <project_root>/node_modules/jest-config/build/normalize.js:747:17 at Array.reduce (<anonymous>) at normalize (<project_root>/node_modules/jest-config/build/normalize.js:608:14) at readConfig (<project_root>/node_modules/jest-config/build/index.js:160:74) at async readConfigs (<project_root>/node_modules/jest-config/build/index.js:424:26) at async runCLI (<project_root>/node_modules/@jest/core/build/cli/index.js:151:59) at async Object.run (<project_root>/node_modules/jest-cli/build/run.js:130:37)
而使用已废弃的--testResultsProcessor命令却能正常工作:
jest --ci --testResultsProcessor=jest-junit
当前环境信息:
- Jest版本:29.7.0(已确认jest-config、jest-cli、jest版本无冲突)
- jest-junit版本:16.0.0
- package.json中的Jest配置:
"jest": { "clearMocks": true, "collectCoverageFrom": [ "tests/**/*.{js,jsx,ts,tsx}" ], "coverageReporters": [ "lcov" ], "resetModules": true, "resetMocks": true, "setupFiles": [ "./tests/helper.ts" ], "testEnvironment": "node", "transform": { "^.+\\.[jt]sx?$": "babel-jest" } },
无单独的jest.config.*配置文件。
原因分析
问题出在命令行参数的解析顺序上:命令末尾添加的**/*.test.[jt]s测试文件匹配规则,被Jest误识别为了第三个reporter参数。
Jest的--reporters参数支持多次指定,每一次--reporters=xxx都会添加一个报告器。当执行jest --ci --reporters=default --reporters=jest-junit **/*.test.[jt]s时,shell会先把**/*.test.[jt]s解析为具体的文件列表(比如tests/fail.test.ts),而Jest会把这些文件名当成额外的--reporters参数值处理,自然找不到对应名称的报告器模块,从而抛出错误。
而使用--testResultsProcessor时,该参数只接受单个值,Jest会正确识别后续的文件匹配规则为测试文件,因此不会出现问题。
解决方法
有两种可行的解决方式:
- 调整参数顺序:把测试文件匹配规则放在
--reporters参数之前,让Jest先识别报告器配置,再处理测试文件:
jest --ci **/*.test.[jt]s --reporters=default --reporters=jest-junit
- 通过配置文件指定reporters:在package.json的jest配置中添加reporters字段,避免命令行参数解析混淆:
"jest": { // 现有配置... "reporters": ["default", "jest-junit"] }
然后执行简化的命令:
jest --ci **/*.test.[jt]s
内容的提问来源于stack exchange,提问作者Alexey Romanov
相关产品推荐
相关产品推荐

