设置 jest --coverage 阈值防止 reducer 漏测分支。
解读
在国内中大型 React + Redux 项目里,“覆盖率不达标不能合并 MR” 已成为 CI 标配。
面试官问“如何防止 reducer 漏测分支”,表面看是 Jest 配置题,实质考察三点:
- 是否理解 reducer 是纯函数,每个分支(switch case、if/else、早期 return)都必须被断言;
- 能否把 行、函数、分支、语句 四类阈值同时卡死,并给出**增量覆盖(diff-cover)**方案,避免“整体达标、增量裸奔”;
- 是否具备 落地经验:把阈值脚本写到
package.json+.gitlab-ci.yml(或 GitHub Actions),让 Pipeline 失败成为硬性门禁,而不是“口头要求”。
知识点
- Jest coverage 四维度:statements、branches、functions、lines,国内规范一般要求 ≥ 90%;
- reducer 分支来源:
switch(action.type)的每个 case、default、条件判断、异常提前 return; - 阈值配置位置:
jest.config.js的coverageThreshold字段; - 增量覆盖工具:
jest --changedSince=origin/main --coverage --coverageThreshold='{}'配合diff-cover生成增量报告; - CI 门禁:GitLab CI 的
coverage:regex +allow_failure: false,或 GitHub Actions 的if: steps.coverage.outputs.lines < 90直接 fail job; - 豁免策略:
/* istanbul ignore next */仅允许在“ truly 不可达”的防御性代码使用,需 MR 评审双人同意。
答案
- 在项目根目录新建
jest.config.js,把阈值卡到 90% 并区分全局与增量:
module.exports = {
testEnvironment: 'jsdom',
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!src/**/*.d.ts',
'!src/index.tsx',
],
coverageThreshold: {
global: {
statements: 90,
branches: 90,
functions: 90,
lines: 90,
},
// 增量覆盖,防止“新代码裸奔”
'./src/store/**/*.js': {
statements: 95,
branches: 95,
functions: 95,
lines: 95,
},
},
coverageReporters: ['text', 'lcov', 'html'],
};
- 在
package.json提供三条命令,本地自检 + CI 强制:
{
"scripts": {
"test": "jest",
"test:coverage": "jest --coverage --watchAll=false",
"test:diff": "jest --changedSince=origin/main --coverage --coverageThreshold='{}' && diff-cover coverage/lcov.info --compare-branch=origin/main --fail-under=90"
}
}
- 在
.gitlab-ci.yml里加 不可跳过的 job:
test:
stage: test
script:
- npm ci
- npm run test:coverage
coverage: '/All files[^|]*\|[^|]*\s+([\d\.]+)/'
allow_failure: false
- 针对 reducer 的典型漏测场景,补全单元测试:
// todosReducer.test.js
import todosReducer from './todosReducer';
describe('todosReducer 分支覆盖', () => {
it('should handle ADD_TODO', () => {
expect(todosReducer([], { type: 'ADD_TODO', payload: 'Learn Jest' }))
.toEqual([{ id: 1, text: 'Learn Jest', done: false }]);
});
it('should handle TOGGLE_TODO', () => {
const initial = [{ id: 1, text: 'Learn Jest', done: false }];
expect(todosReducer(initial, { type: 'TOGGLE_TODO', payload: 1 }))
.toEqual([{ id: 1, text: 'Learn Jest', done: true }]);
});
it('should return initial state when unknown type', () => {
expect(todosReducer(undefined, { type: 'FOO' })).toEqual([]);
});
});
- 提交 MR 后,Pipeline 因覆盖率低于 90% 失败,开发者必须补充测试或书面说明豁免原因,由架构师 Review 后方可合并——把“覆盖率”从指标变成门禁。
拓展思考
-
“ 100% 覆盖是否等于无 Bug?”
面试官常追问。答:覆盖只证明“代码跑到”,不证明“业务正确”;需要 property-based testing(fast-check) 生成非法 action,验证 reducer 是否始终满足“相同输入相同输出”的纯函数性质。 -
如何防止“阈值通胀”导致开发效率下降?
建议 分模块设阈值:核心资金结算 reducer 必须 100%,普通配置型 reducer 可 85%;配合jest.config.js的projects字段做多配置,让“高内聚、低耦合”体现在测试策略上。 -
Monorepo 场景下如何共享阈值?
使用jest.config.base.js抽离公共阈值,各 package 通过preset: '../../jest.config.base'继承,保证百仓库同标,避免“每个团队各自为政”。 -
把覆盖率报告上传到内部 SonarQube,再配置 质量阈 “新增分支覆盖 < 90% 即失败”,实现“二次守门”,即使开发者本地绕过,也无法进入主干——国内一线厂普遍采用的双保险方案。