5月28日 04:25

Jest 中 test.skip 和 test.only 有什么区别?

Jest 用 .skip 排除测试,用 .only 聚焦测试——两种思路,作用对象都可以是单个 test 或整个 describe。

跳过(skip):标记的测试不执行,但会在报告中显示为 skipped。

javascript
test.skip('暂时不跑', () => { ... }); // 等价于 xtest / xit describe.skip('整组跳过', () => { ... }); // 等价于 xdescribe

聚焦(only):只执行标记的测试/套件,其余全部跳过。

javascript
test.only('只跑这个', () => { ... }); // 等价于 fit / it.only describe.only('只跑这组', () => { ... }); // 等价于 fdescribe

关键区别:skip 是"排除法",only 是"聚焦法"。多个 only 会全部执行——它不是"仅这一个",而是"至少这些"。

追问

test.skip 和 describe.skip 什么时候用?

单个用例有问题用 test.skip,整个模块依赖没准备好用 describe.skip。常见场景:某个 API 还没上线、测试依赖的外部服务挂了。但千万别把 skip 当摆设——CI 里积压的 skip 测试是技术债,团队应有清理机制。

.only 提交到 CI 会怎样?

CI 只跑被 only 标记的测试,大量测试被静默跳过,回归缺陷直接漏到线上。防御手段:eslint-plugin-jest 的 no-focused-tests 规则,在 pre-commit 或 CI 阶段拦截。也有团队在 CI 启动时用自定义 Jest Environment 强制把 .only 和 .skip 还原成普通函数,确保全量执行。

条件性跳过怎么写?

javascript
const skipInCI = process.env.CI ? test.skip : test; skipInCI('本地才跑的测试', () => { ... });

或用 Jest 28+ 的 describe.skipIf / test.skipIf

javascript
test.skipIf(process.env.CI)('本地才跑', () => { ... });

命令行过滤和 .only 有什么区别?

jest --testNamePattern="should add" 是纯命令行行为,不改代码,不污染仓库。.only 写在代码里,容易误提交。日常调试优先用命令行参数或 --onlyChanged,只有需要在特定文件内反复调试时才用 .only。

怎么防止团队积累大量 skip 测试?

三招配合:1) ESLint 规则 no-disabled-tests 配合 warn,skip 超过阈值就 CI 失败;2) 要求 skip 必须带注释说明原因和预期恢复时间;3) 每次发版前用 jest --listTests --onlyFailures 扫一遍,skip 数量纳入代码健康指标。

标签:Jest