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:

javascript
test.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:

javascript
describe.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:

javascript
test.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:

javascript
describe.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:

javascript
const 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 .only for debugging, remove when done
  • Use .skip to temporarily disable failing tests
  • Avoid committing code with .only or .skip
  • Use command line options for temporary test filtering
  • Use --onlyFailures in CI/CD to run only failed tests
标签:Jest