Jest生成覆盖率报告报'No element indexed by 9'错误求助
排查与解决指南
问题背景
- 技术栈:Next.js + Redux Toolkit 项目,使用 Jest 运行测试,通过 MSW 模拟 RTK Query 发起的第三方外部 API 请求,当前仅模拟测试实际调用的 RTK Query 端点,未做全量端点模拟。
- 异常表现:
- 执行
npm run test、不生成覆盖率报告时,所有测试运行正常。 - 执行
npm run test -- --coverage生成覆盖率报告时,所有测试全部失败,抛出统一错误:
- 执行
- Test suite failed to run No element indexed by 9 at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9) at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30) at mapSourcePosition (node_modules/source-map-support/source-map-support.js:214:42) at wrapCallSite (node_modules/source-map-support/source-map-support.js:358:20) at node_modules/source-map-support/source-map-support.js:399:26 at Array.map (<anonymous>) at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:398:30)
- 验证结果:将 MSW 的 handlers 设为空数组后错误消失,此时依赖 API 模拟的测试会按预期失败,其余测试可正常运行。
分步排查方案
- 第一步:修复 source-map 版本冲突
这个No element indexed by 9是旧版source-map@0.6.x的典型bug,当解析不符合预期的 source map 时会触发数组索引越界。先执行npm ls source-map查看依赖树,如果发现source-map-support下嵌套了0.6.x版本的source-map,直接在项目devDependencies中安装source-map@^0.7.4,通过依赖提升覆盖嵌套的旧版本,多数场景下这一步就能解决问题。 - 第二步:调整 Jest 覆盖率配置
Jest 默认使用的 istanbul 覆盖率 provider 会对收集范围内的所有文件插桩,同时调用 source-map-support 做错误栈映射,很容易触发上述兼容问题。修改jest.config.js配置:module.exports = { // 保留原有其他配置 coverageProvider: 'v8', // 切换为V8引擎内置的覆盖率收集能力,绕开istanbul的source-map解析逻辑 collectCoverageFrom: [ '**/*.{js,jsx,ts,tsx}', '!**/node_modules/**', '!**/.next/**', '!**/mocks/**' // 排除MSW相关的mock文件,不对这类不需要统计覆盖率的文件做插桩 ] } - 第三步:修正 MSW 测试环境初始化逻辑
- 不要在全局setup文件中固定注册所有handler,改为在单测文件/用例中按需注册实际用到的handler,用例执行完成后及时重置,避免未被模拟的RTK Query请求在测试退出阶段触发未捕获异常。
- 确认MSW生命周期钩子配置正确:
beforeAll阶段启动server,afterAll阶段关闭server,afterEach阶段执行server.resetHandlers()清理用例间的handler污染。 - 给MSW server加一个全局兜底handler,对所有未被模拟的请求直接返回500错误并打印请求地址,避免未匹配的请求静默挂起,在覆盖率收集阶段触发异常栈解析。
- 第四步:排查Next.js编译配置冲突
如果项目开启了SWC压缩、自定义SWC插件,在测试环境下关闭SWC的源码压缩和自定义source map生成,使用babel-jest处理测试文件转译,避免SWC生成的非标准格式source map触发解析bug。
内容的提问来源于stack exchange,提问作者Gurnzbot
相关产品推荐
相关产品推荐

