| | |

Vitest 21 🧪 Test Filtering — test.only, test.skip, and test.todo

⏱️ Estimated read: 9 min | |

As modern testing suites scale to thousands of unit and integration specifications, running the entire test repository during every local code change introduces unnecessary execution latency. Developers frequently need to isolate a single failing function, temporarily bypass environment-sensitive or broken assertions, or placeholder future specifications before writing implementation logic. Vitest provides native, high-performance test filtering modifiers—test.only, test.skip, and test.todo—that integrate seamlessly with Vite’s fast transformation pipeline.

Configuring and mastering test filters allows engineers to streamline local debugging cycles, document upcoming test requirements cleanly, and prevent flaky test regressions from breaking continuous integration builds. This chapter explores method-level modifiers, suite-level scoping, CLI filtering flags, and best practices for managing test states effectively.

Key point: Vitest provides built-in test modifiers like test.only, test.skip, and test.todo to isolate specific test executions, bypass failing environments, and document pending implementations without deleting code.

Why X exists

The debugging isolation problem.

When a test suite contains hundreds of files, executing every single assertion to troubleshoot a single failing function wastes valuable development time and floods the terminal with irrelevant noise.

The flaky test bottleneck challenge.

External network dependencies or race conditions can cause occasional test failures that block urgent pull requests before developers have time to refactor the underlying code.

The incomplete feature documentation gap.

Writing code without test coverage creates technical debt, but tracking planned tests in external issue trackers often divorces requirements from the codebase itself.

The CI/CD pipeline protection barrier.

Accidentally committing focused test modifiers (.only) can silently disable 99% of a test suite in production pipelines, creating a false sense of security if not caught by pre-commit hooks.

The suite maintenance efficiency challenge.

Permanently deleting failing tests loses historical context, whereas commenting out blocks leaves dead code that fails syntax checks or type-checking scripts.

a. Isolating Executions with test.only and describe.only

When investigating a specific regression, executing the entire test file can be inefficient. Appending .only to test(), it(), or describe() instructs Vitest to run exclusively the marked test cases or suites while ignoring all other sibling blocks in the file.

TypeScript

import { describe, expect, it } from 'vitest';

function calculateTax(amount: number, rate: number): number {
  return amount * (1 + rate);
}

describe('Tax Calculation Suite', () => {
  // This test will be ignored because another block is marked with .only
  it('calculates standard tax correctly', () => {
    expect(calculateTax(100, 0.2)).toBe(120);
  });

  // Vitest runs ONLY this test block
  it.only('calculates zero-rate tax correctly', () => {
    expect(calculateTax(100, 0)).toBe(100);
  });
});

Using test.only focuses the test runner’s output on the immediate problem area. Similarly, describe.only isolates an entire suite of related tests, making it ideal for large component validation files where only one sub-system is undergoing active debugging.

b. Bypassing Failing or Unsupported Tests with test.skip and it.skip

During environment migrations, refactoring phases, or temporary infrastructure outages, certain tests may fail due to external factors unrelated to the code logic. Rather than deleting these assertions, developers can append .skip to bypass execution safely.

TypeScript

import { describe, expect, it } from 'vitest';

function fetchRemoteConfiguration(): Promise<{ timeout: number }> {
  return Promise.resolve({ timeout: 5000 });
}

describe('Remote Configuration Suite', () => {
  it('loads remote configuration successfully', async () => {
    const config = await fetchRemoteConfiguration();
    expect(config.timeout).toBe(5000);
  });

  // Bypassed temporarily due to external staging server downtime
  it.skip('synchronizes remote webhook subscriptions', async () => {
    const status = await syncWebhooks();
    expect(status).toBe(true);
  });
});

When Vitest encounters .skip, it explicitly marks the test as skipped in the terminal summary report, ensuring teams maintain visibility over temporarily inactive assertions without failing build pipelines.

c. Documenting Unimplemented Specifications with test.todo

Test-driven development (TDD) and architectural planning often require outlining expected behaviors before the underlying functions exist. Vitest provides test.todo to declare placeholder test specifications that appear in test reports as pending reminders.

TypeScript

import { describe, test } from 'vitest';

describe('User Authentication Service', () => {
  test('authenticates valid credentials', () => {
    // Implemented logic here
  });

  // Placeholder for future implementation
  test.todo('handles multi-factor authentication token verification');

  // Placeholder for security enhancement
  test.todo('locks account after five consecutive failed login attempts');
});

Unlike skipped tests, test.todo does not execute any callback function and serves purely as a descriptive contract. This keeps feature roadmaps visible directly inside the test runner output, encouraging developers to close coverage gaps over time.

Complete Example Session

TypeScript

// ============================================
// PART 1: MODULE IMPORTS SETUP
// ============================================
import { describe, expect, it, test } from 'vitest';

TypeScript

// ============================================
// PART 2: CORE BUSINESS LOGIC FUNCTION
// ============================================
export function validateInventoryStock(qty: number, threshold: number): boolean {
  if (qty < 0) throw new Error('Quantity cannot be negative');
  return qty >= threshold;
}

TypeScript

// ============================================
// PART 3: STANDARD ACTIVE TEST CASE
// ============================================
describe('Inventory Validation Suite', () => {
  it('returns true when stock meets threshold', () => {
    const isValid = validateInventoryStock(15, 10);
    expect(isValid).toBe(true);
  });

TypeScript

// ============================================
// PART 4: ISOLATING SPECIFIC TESTS WITH .only
// ============================================
  it.only('validates exact threshold boundary conditions', () => {
    const isValid = validateInventoryStock(10, 10);
    expect(isValid).toBe(true);
  });

TypeScript

// ============================================
// PART 5: BYPASSING LEGACY TESTS WITH .skip
// ============================================
  it.skip('legacy database stock synchronization check', () => {
    // Deprecated legacy check bypassed during migration
    expect(true).toBe(true);
  });

TypeScript

// ============================================
// PART 6: TODO PLACEHOLDER FOR UPCOMING FEATURE
// ============================================
  test.todo('implements automated low-stock email alert dispatch');
});

TypeScript

// ============================================
// PART 7: SUITE-LEVEL DESCRIBE.ONLY ISOLATION
// ============================================
describe.only('Isolated Module Verification', () => {
  test('verifies core module integrity', () => {
    expect(true).toBe(true);
  });
});

TypeScript

// ============================================
// PART 8: CONDITIONAL SKIPPING DYNAMICS
// ============================================
describe('Conditional Execution', () => {
  const isCIEnvironment = process.env.CI === 'true';

  it('runs local performance benchmark', () => {
    if (isCIEnvironment) {
      // Dynamically skip inside test body if condition fails
      return;
    }
    expect(1 + 1).toBe(2);
  });
});

TypeScript

// ============================================
// PART 9: ERROR BOUNDARY ASSERTION
// ============================================
describe('Error Handling Validation', () => {
  it('throws error on negative stock inputs', () => {
    expect(() => validateInventoryStock(-5, 10)).toThrow('Quantity cannot be negative');
  });
});

TypeScript

// ============================================
// PART 10: TEST EXECUTION FINALIZATION
// ============================================
// All filtered test states resolved correctly by Vitest test runner

This ten-part sequence demonstrates how to combine active test cases, focused .only selectors, skipped assertions, and .todo placeholders within a structured Vitest session.

Quick Reference

Test Filtering Modifiers

ModifierTarget ScopeExecution Behavior
test.only / it.onlySingle test caseRuns exclusively the marked test(s), ignoring all others
describe.onlyTest suite blockRuns exclusively the marked describe suite
test.skip / it.skipSingle test caseBypasses test execution and marks it skipped in reports
describe.skipTest suite blockBypasses an entire test suite
test.todoPlaceholder specDocuments pending tests without running code

CLI Filtering Flags

FlagPurposeExample
-t, --testNamePatternRuns tests matching regex stringvitest -t "Inventory"
--runRuns tests once without watch modevitest run --dir src/auth

Best Practices

✅ Do This:

TypeScript

it.skip('skips unstable network test during migration', () => { ... });      // ✅

❌ Don’t Do This:

TypeScript

// comment out entire test block to disable it                               // ❌

✅ Do This:

TypeScript

test.todo('implement OAuth2 refresh token rotation mechanism');             // ✅

❌ Don’t Do This:

TypeScript

it('implement OAuth2 refresh token rotation', () => { /* empty */ });        // ❌

✅ Do This:

TypeScript

vitest -t "specific test name"                                              // ✅

❌ Don’t Do This:

TypeScript

// leave test.only committed in main branch before opening PR                // ❌

✅ Do This:

TypeScript

describe.only('Active Debugging Suite', () => { ... });                     // ✅

❌ Don’t Do This:

TypeScript

// mix multiple conflicting .only modifiers across unrelated files           // ❌

Common Pitfalls

PitfallWhy It HappensFix
Committing test.only to main branchForgetting to remove temporary focus filters before pushing codeUtilize pre-commit hooks (Husky / lint-staged) to block .only commits
Skipped tests masking critical bugsLeaving test.skip active indefinitely without creating tracking ticketsAdd issue reference comments above skipped tests (// TODO: Fix in JIRA-402)
test.todo failing CI buildsMistakenly expecting test.todo placeholders to execute or throw errorsUnderstand that todos are documentation only and never fail builds
Name pattern mismatch with -tPassing incorrect regex strings that fail to match test titlesUse clear, descriptive test names and test CLI patterns locally first
Suite-level .only hiding unrelated filesConfusing file-level test isolation with workspace-wide executionUse file path arguments in CLI (vitest src/auth.test.ts) for file-level isolation

Real-World Examples

1. Isolating a Single Failing API Test with it.only

TypeScript

it.only('returns 200 OK for valid user payload', async () => {
  const res = await api.post('/users', { name: 'Alice' });
  expect(res.status).toBe(200);
});

2. Bypassing External Payment Gateway Tests During Local Offline Work

TypeScript

it.skip('processes Stripe webhook signature verification', async () => {
  const verified = await stripe.verifyWebhook(payload, sig);
  expect(verified).toBe(true);
});

3. Documenting Future Rate-Limiting Requirements with test.todo

TypeScript

test.todo('enforces rate limit of 100 requests per minute per IP address');

4. Scoping Debugging to an Entire Controller Suite

TypeScript

describe.only('Order Controller Integration Suite', () => {
  it('creates order successfully', () => { ... });
});

5. Skipping Legacy Database Migration Tests Temporarily

TypeScript

describe.skip('Legacy Oracle Database Adapter', () => {
  it('connects to legacy schema', () => { ... });
});

6. Running Tests Matching a Specific Pattern via CLI

Bash

npx vitest -t "Tax Calculation"

7. Combining test.skip with Environment Checks

TypeScript

it('runs enterprise audit log export', () => {
  if (process.env.TIER !== 'enterprise') return;
  expect(exportAuditLogs()).resolves.toBe(true);
});

8. Documenting Pending Security Hardening Specs

TypeScript

test.todo('ensures JWT tokens are stored in secure httpOnly cookies');

9. Isolating Parameterized Test Cases

TypeScript

it.only('validates admin role permission matrix', () => {
  expect(checkPermission('admin', 'delete')).toBe(true);
});

10. Skipping UI Snapshot Tests During Headless CLI Runs

TypeScript

it.skip('matches mobile layout snapshot representation', () => {
  expect(renderMobileView()).toMatchSnapshot();
});

Visual

Test Filtering Execution Flow

┌────────────────────────────────────────────────────────┐
│  Vitest Discovers Test File Suite Specifications       │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│  Evaluate Modifiers (.only, .skip, .todo)              │
├───────────────────────────┬────────────────────────────┤
│  • .only ──► Runs Exclusively (Skips Sibling Blocks)   │
│  • .skip ──► Bypasses Execution (Marked Skipped)       │
│  • .todo ──► Registers as Pending Documentation        │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│  Generate Terminal Summary Report & Exit Code          │
└────────────────────────────────────────────────────────┘

Modifier Scope Hierarchy

┌────────────────────────────────────────────────────────┐
│ describe('Suite', () => {                              │
│   it.skip('Skipped Test') ──► Bypassed                 │
│   it.only('Focused Test') ──► Runs Exclusively         │
│   test.todo('Pending')    ──► Documented               │
│ })                                                     │
└────────────────────────────────────────────────────────┘

Debugging Isolation Workflow

┌────────────────────────────────────────────────────────┐
│ Developer Identifies Failing Regression                │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│ Append .only to target test() or describe()            │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│ Execute `npx vitest` ──► Instant Feedback Loop         │
└────────────────────────────────────────────────────────┘

Summary

ItemValue
ConceptTest Filtering and Isolation in Vitest
Focus Modifiertest.only, it.only, describe.only
Bypass Modifiertest.skip, it.skip, describe.skip
Documentation Modifiertest.todo
CLI Pattern Matching-t, --testNamePattern
Primary BenefitAccelerates local debugging and documents roadmaps
Execution StateSkipped tests report explicitly; todos remain pending
Best PracticeRemove .only modifiers before committing code
Target IntegrationSeamless Vite module graph execution
Maintenance RolePrevents test deletion while handling flaky specs

Key takeaways:

  • Isolate failures instantly. Use .only on test cases or describe blocks to focus test execution exclusively on the code under active debugging.
  • Bypass flaky assertions safely. Apply .skip to temporarily deactivate environment-sensitive or broken tests without deleting code or breaking syntax.
  • Document pending requirements. Utilize test.todo as a clean, in-code placeholder for upcoming features and unwritten specifications.
  • Leverage CLI pattern matching. Combine test modifiers with the -t CLI flag to filter execution precisely by test name strings.
  • Protect CI pipelines. Ensure .only modifiers are stripped before pushing changes to prevent silent test omissions in production build pipelines.
  • Maintain historical context. Keep skipped and todo tests in the repository with descriptive comments to preserve engineering intent and track technical debt.

Remember: Effective test filtering transforms massive testing suites into agile diagnostic tools. By mastering .only, .skip, and .todo, engineering teams can isolate regressions rapidly, document planned features cleanly, and maintain robust test hygiene across complex codebases.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!