5月28日 04:25
How to skip and isolate tests in Jest? How to use test.skip, test.only, and describe.only?
Jest provides multiple methods for skipping and isolating tests to focus on specific tests during development:
1. Skipping Individual Tests:
javascripttest.skip('this test is skipped', () => { expect(true).toBe(false); }); // Or use xtest xtest('this test is also skipped', () => { expect(true).toBe(false); });
2. Skipping Test Suites:
javascriptdescribe.skip('skipped suite', () => { test('this test will not run', () => { expect(true).toBe(false); }); }); // Or use xdescribe xdescribe('also skipped suite', () => { test('this test will not run', () => { expect(true).toBe(false); }); });
3. Running Only Specific Tests:
javascripttest.only('only this test runs', () => { expect(true).toBe(true); }); test('this test is skipped', () => { expect(true).toBe(false); }); // Or use fit fit('only this test runs', () => { expect(true).toBe(true); });
4. Running Only Specific Test Suites:
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); }); }); // Or use fdescribe fdescribe('only this suite runs', () => { test('this test runs', () => { expect(true).toBe(true); }); });
5. Conditional Test Skipping:
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. Using Command Line to Filter Tests:
bash# Run only tests matching pattern jest --testNamePattern="should add" # Run only specific file jest path/to/test.spec.js # Run tests related to changed files jest --onlyChanged
Best Practices:
- Use
.onlyfor debugging, remove when done - Use
.skipto temporarily disable failing tests - Avoid committing code with
.onlyor.skip - Use command line options for temporary test filtering
- Use
--onlyFailuresin CI/CD to run only failed tests