Tests Inside Source Files in Vitest

From the Vitest cheat sheet · In-Source Testing · verified Nov 2026

Tests Inside Source Files

Use import.meta.vitest blocks and strip them from production builds

typescript
// src/math.ts
export const add = (...n: number[]) => n.reduce((a, b) => a + b, 0)

if (import.meta.vitest) {
  const { test, expect } = import.meta.vitest
  test('add', () => {
    expect(add(1, 2, 3)).toBe(6)
  })
}

// vitest.config.ts: test: { includeSource: ['src/**/*.ts'] }
💡 Great for small pure utilities where tests double as docs
📌 Define import.meta.vitest as undefined so builds drop the tests
⚠️ Keep larger suites in separate files so source stays readable
🟢 Add vitest/importMeta to tsconfig types for TypeScript support
in-sourceimport.meta.vitest

Continue with Vitest

Save the full cheat sheet or work through every related task.

Back to the full Vitest cheat sheet