| | |

Vitest 22 🧪 In-Source Testing — import.meta.vitest and colocated tests

⏱️ Estimated read: 9 min | |

Traditional unit testing architectures require creating a separate mirror file for every implementation module (e.g., math.ts paired with math.test.ts), which often forces developers to export internal helper functions solely for testing purposes or switch contexts between distant directory trees. In-source testing bridges this gap by embedding unit tests directly within the source implementation file using an if (import.meta.vitest) execution block.

Vitest leverages Vite’s underlying transformation pipeline to evaluate these colocated test blocks during development and test execution. During production bundling, setting import.meta.vitest to undefined allows modern bundlers like Vite, Rollup, or Rolldown to eliminate the test code entirely via dead-code removal. This chapter explores how to configure include sources, structure in-source test blocks, manage production build optimization, and write robust unit tests alongside private application logic.

Key point: In-source testing embeds unit tests directly inside implementation files using if (import.meta.vitest), eliminating the need to export private helper functions while allowing bundlers to strip test suites completely during production builds.

Why X exists

The test file separation problem.

Maintaining parallel directory structures for source and test files introduces unnecessary file-switching overhead and fragments related codebase logic across distant paths.

The encapsulation friction problem.

Developers frequently encounter scenarios where critical internal helper functions must be exported solely to make them accessible to external test files, weakening module encapsulation boundaries.

The production dead-code elimination challenge.

Bundling test utilities into production artifacts bloats bundle sizes and exposes internal implementation surfaces unless build tools automatically strip test blocks.

The feedback loop latency challenge.

Navigating between separate test files and implementation modules slows down local iteration speed during rapid prototyping and algorithmic development.

The colocation clarity challenge.

Keeping unit specifications immediately adjacent to the code they verify ensures that refactoring implementation details prompts immediate inspection of local unit behavior.

a. Configuring Vitest for Source Inclusion

By default, Vitest searches for dedicated test files matching naming conventions like .test.ts or .spec.ts. To enable discovery of in-source tests inside standard source files, you must configure the includeSource glob option in your Vitest configuration file and define import.meta.vitest as undefined for production builds.

TypeScript

// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    includeSource: ['src/**/*.{js,ts}'],
  },
  define: {
    'import.meta.vitest': 'undefined',
  },
});

This configuration instructs Vitest to scan all JavaScript and TypeScript files within the src directory for in-source test blocks while preparing the bundler to eliminate those blocks during production compilation.

b. Writing In-Source Tests with import.meta.vitest

Within your implementation module, place an if (import.meta.vitest) conditional block at the bottom of the file. Destructure test utilities directly from import.meta.vitest to write assertions alongside your private or exported functions.

TypeScript

// src/utils.ts
export function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max);
}

if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  
  it('clamps values within bounds', () => {
    expect(clamp(5, 0, 10)).toBe(5);
    expect(clamp(-5, 0, 10)).toBe(0);
    expect(clamp(15, 0, 10)).toBe(10);
  });
}

Because import.meta.vitest is only defined during testing environments, static analysis and production compilers treat the conditional block as unreachable code, ensuring zero runtime overhead in production.

c. TypeScript Integration and Import Meta Types

To prevent TypeScript from throwing compilation errors when encountering import.meta.vitest, you must include the appropriate type definitions in your project’s TypeScript configuration.

JSON

{
  "compilerOptions": {
    "types": [
      "node",
      "vitest/importMeta"
    ]
  }
}

Adding vitest/importMeta to the compiler options extends the global ImportMeta interface, granting full type safety and autocompletion for test utilities accessed through import.meta.vitest.

Complete Example Session

TypeScript

// ============================================
// PART 1: CONFIGURATION SETUP (vitest.config.ts)
// ============================================
export const vitestConfig = {
  test: { includeSource: ['src/**/*.ts'] },
  define: { 'import.meta.vitest': 'undefined' },
};

TypeScript

// ============================================
// PART 2: TYPESCRIPT CONFIGURATION (tsconfig.json)
// ============================================
export const tsConfigMeta = {
  compilerOptions: { types: ['vitest/importMeta'] },
};

TypeScript

// ============================================
// PART 3: CORE IMPLEMENTATION MODULE (src/math.ts)
// ============================================
export function calculatePercentage(part: number, total: number): number {
  if (total === 0) return 0;
  return Number(((part / total) * 100).toFixed(2));
}

TypeScript

// ============================================
// PART 4: PRIVATE HELPER FUNCTION ENCAPSULATION
// ============================================
function roundToTwo(num: number): number {
  return Math.round(num * 100) / 100;
}

TypeScript

// ============================================
// PART 5: IN-SOURCE TEST BLOCK DEFINITION
// ============================================
if (import.meta.vitest) {
  const { describe, it, expect } = import.meta.vitest;
  
  describe('calculatePercentage in-source suite', () => {
    it('computes correct percentage ratio', () => {
      expect(calculatePercentage(25, 200)).toBe(12.5);
    });
  });
}

TypeScript

// ============================================
// PART 6: TESTING PRIVATE HELPERS DIRECTLY
// ============================================
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  
  it('rounds numbers correctly via private helper', () => {
    expect(roundToTwo(10.5678)).toBe(10.57);
  });
}

TypeScript

// ============================================
// PART 7: ZERO-TOTAL EDGE CASE HANDLING
// ============================================
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  
  it('returns zero when total denominator is zero', () => {
    expect(calculatePercentage(50, 0)).toBe(0);
  });
}

TypeScript

// ============================================
// PART 8: CLI IN-SOURCE EXECUTION COMMAND
// ============================================
export const testCommand = 'npx vitest --includeSource src/math.ts';

TypeScript

// ============================================
// PART 9: PRODUCTION DEAD-CODE ELIMINATION
// ============================================
// Bundler replaces import.meta.vitest with undefined and strips block

TypeScript

// ============================================
// PART 10: SESSION FINALIZATION
// ============================================
// In-source test execution completed successfully across all parts

Quick Reference

Configuration Properties

PropertyTargetPurpose
includeSourcevitest.config.tsGlob patterns identifying source files containing tests
definevitest.config.tsReplaces import.meta.vitest with undefined for builds
typestsconfig.jsonIncludes vitest/importMeta for TypeScript definitions

Execution Context APIs

API MemberSourcePurpose
import.meta.vitestMeta ObjectProvides test utilities (it, describe, expect)
if (import.meta.vitest)Runtime GuardEnsures test code executes only during test runs

Best Practices

✅ Do This:

TypeScript

if (import.meta.vitest) { const { it, expect } = import.meta.vitest; }         // ✅

❌ Don’t Do This:

TypeScript

import { it, expect } from 'vitest'; // imports test utils in production code // ❌

✅ Do This:

TypeScript

includeSource: ['src/**/*.ts']                                                // ✅

❌ Don’t Do This:

TypeScript

includeSource: ['**/*'] // scans node_modules and build output directories  // ❌

✅ Do This:

TypeScript

define: { 'import.meta.vitest': 'undefined' }                                 // ✅

❌ Don’t Do This:

TypeScript

// omit define plugin, leaking test code into production bundles            // ❌

Common Pitfalls

PitfallWhy It HappensFix
Production bundle containing test codeFailing to configure define: { 'import.meta.vitest': 'undefined' } in bundlerAdd the define substitution rule to your Vite or Rollup configuration
TypeScript “Property ‘vitest’ does not exist” errorMissing vitest/importMeta entry in tsconfig.json compiler optionsAdd "types": ["vitest/importMeta"] to your TypeScript configuration
Tests not running in source filesOmission of includeSource glob pattern inside Vitest configurationConfigure includeSource to target your application source directories

Real-World Examples

1. Testing Private URL Formatter Helpers

TypeScript

function formatSlug(text: string): string {
  return text.toLowerCase().replace(/\s+/g, '-');
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('formats slugs', () => { expect(formatSlug('Hello World')).toBe('hello-world'); });
}

2. Colocated Validation Logic Testing

TypeScript

export function isEmailValid(email: string): boolean {
  return email.includes('@');
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('validates email', () => { expect(isEmailValid('test@example.com')).toBe(true); });
}

3. Mathematical Utility In-Source Suite

TypeScript

export const TAX_RATE = 0.2;
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('has correct tax rate', () => { expect(TAX_RATE).toBe(0.2); });
}

4. String Truncation Helper

TypeScript

function truncate(str: string, len: number): string {
  return str.length > len ? str.slice(0, len) + '...' : str;
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('truncates strings', () => { expect(truncate('LongString', 4)).toBe('Long...'); });
}

5. Object Property Default Merging

TypeScript

function mergeConfig(userCfg: any) {
  return { timeout: 1000, ...userCfg };
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('merges config', () => { expect(mergeConfig({ timeout: 500 })).toEqual({ timeout: 500 }); });
}

6. Array Chunking Algorithm

TypeScript

function chunkArray<T>(arr: T[], size: number): T[][] {
  return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('chunks array', () => { expect(chunkArray([1, 2, 3], 2)).toEqual([[1, 2], [3]]); });
}

7. Enum Parsing Helper

TypeScript

enum Status { ACTIVE = 'ACTIVE' }
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('matches enum value', () => { expect(Status.ACTIVE).toBe('ACTIVE'); });
}

8. Cryptographic Hash Salt Generation

TypeScript

function generateSalt(): string {
  return Math.random().toString(36);
}
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('generates string salt', () => { expect(typeof generateSalt()).toBe('string'); });
}

9. Date Formatting Utility

TypeScript

function getYear(date: Date): number { return date.getFullYear(); }
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('gets year', () => { expect(getYear(new Date('2026-01-01'))).toBe(2026); });
}

10. Bitwise Permission Checker

TypeScript

const READ = 1;
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest;
  it('verifies bitwise flag', () => { expect(READ & 1).toBe(1); });
}

Visual

In-Source Testing Compilation Pipeline

┌────────────────────────────────────────────────────────┐
│  Source File with if (import.meta.vitest) Block        │
└───────────────────────────┬────────────────────────────┘
                            │
           ┌────────────────┴────────────────┐
           ▼                                 ▼
┌───────────────────────┐         ┌───────────────────────┐
│ Development / Testing │         │ Production Bundling   │
│ Vitest Runs Block     │         │ Vite Strips via Define│
└───────────────────────┘         └───────────────────────┘

Colocated Source vs Mirror File Architecture

┌────────────────────────────────────────────────────────┐
│  TRADITIONAL: math.ts ──► Separate math.test.ts        │
├────────────────────────────────────────────────────────┤
│  IN-SOURCE:   math.ts (Contains implementation & tests)│
└────────────────────────────────────────────────────────┘

TypeScript ImportMeta Augmentation Flow

┌────────────────────────────────────────────────────────┐
│ tsconfig.json includes "types": ["vitest/importMeta"]    │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│ IDE Recognizes import.meta.vitest with Full Autocomplete│
└────────────────────────────────────────────────────────┘

Summary

ItemValue
ConceptIn-Source Testing in Vitest
Core Mechanismif (import.meta.vitest) execution block
Configuration OptionincludeSource glob setting in Vitest config
Build Optimizationdefine: { 'import.meta.vitest': 'undefined' }
TypeScript Integrationvitest/importMeta type definition inclusion
Primary BenefitColocates unit tests with private implementation code
Encapsulation AdvantageEliminates need to export private helpers for tests
Production SafetyDead-code elimination strips test blocks entirely
Execution CommandVitest evaluates matched source files automatically
Developer ExperienceSpeeds up local feedback loops and refactoring

Key takeaways:

  • Colocate implementation and tests. Keep unit specifications right next to private helper functions inside source files to maintain tight contextual coupling.
  • Guard test blocks with runtime checks. Wrap tests inside if (import.meta.vitest) so they remain dormant during normal runtime execution.
  • Configure source inclusion globs. Use the includeSource configuration property to instruct Vitest to discover tests inside application source files.
  • Enable production dead-code stripping. Define import.meta.vitest as undefined in your bundler configuration to eliminate test code from production artifacts.
  • Extend TypeScript meta types. Add vitest/importMeta to your tsconfig.json types array to ensure full type safety and autocompletion.
  • Avoid exporting internal test hooks. Test private functions directly without polluting module exports or weakening encapsulation boundaries.

Remember: In-source testing transforms how developers structure unit tests by bringing specifications directly into implementation files. By combining import.meta.vitest with robust bundler dead-code elimination, engineering teams can achieve maximum test colocation without compromising production bundle efficiency or module encapsulation.

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!