Jest 提供了多种跳过和隔离测试的方法,用于在开发过程中专注于特定测试:
1. 跳过单个测试:
javascripttest.skip('this test is skipped', () => { expect(true).toBe(false); }); // 或使用 xtest xtest('this test is also skipped', () => { expect(true).toBe(false); });
2. 跳过测试套件:
javascriptdescribe.skip('skipped suite', () => { test('this test will not run', () => { expect(true).toBe(false); }); }); // 或使用 xdescribe xdescribe('also skipped suite', () => { test('this test will not run', () => { expect(true).toBe(false); }); });
3. 只运行特定测试:
javascripttest.only('only this test runs', () => { expect(true).toBe(true); }); test('this test is skipped', () => { expect(true).toBe(false); }); // 或使用 fit fit('only this test runs', () => { expect(true).toBe(true); });
4. 只运行特定测试套件:
javascriptdescribe.only('only this suite runs', () => { test('this test runs', () => { expect(true).toBe(true); }); }); describe('this suite is skipped', () => { test('this test is skipped', () => { expect(true).toBe(false); }); }); // 或使用 fdescribe fdescribe('only this suite runs', () => { test('this test runs', () => { expect(true).toBe(true); }); });
5. 条件性跳过测试:
javascriptconst skipIf = (condition, testName, testFn) => { const testOrSkip = condition ? test.skip : test; testOrSkip(testName, testFn); }; skipIf(process.env.CI, 'skip in CI', () => { expect(true).toBe(true); });
6. 使用命令行过滤测试:
bash# 只运行匹配模式的测试 jest --testNamePattern="should add" # 只运行特定文件 jest path/to/test.spec.js # 只运行修改过的文件相关测试 jest --onlyChanged
最佳实践:
- 使用
.only进行调试,完成后移除 - 使用
.skip暂时禁用失败的测试 - 避免提交包含
.only或.skip的代码 - 使用命令行选项进行临时测试过滤
- 在 CI/CD 中使用
--onlyFailures只运行失败的测试