Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run Vitest In-Source Unit Testing & Instant ESM Execution in Autonomous AI Agents

Step-by-step SOP to install and run Vitest In-Source Unit Testing in Codex, Claude Code, and Cursor. Includes verified prompts, configs, and troubleshooting.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents frequently default to generating decoupled unit test files (*.test.ts) across distant directory trees. In rapid feature iteration and complex utility pipelines, this creates context fragmentation: agents lose track of private implementation details, hallucinate stale function signatures, and waste prompt tokens switching between source and test files. Moreover, agents often forget to prevent test logic from leaking into production production bundles, resulting in bloated build artifacts. Vitest In-Source Testing bridges this gap by co-locating deterministic test suites directly within the implementation source using conditional blocks (if (import.meta.vitest)). When paired with this SKILL.md specification, coding agents (Codex, Claude Code, Cursor, Windsurf) are constrained by deterministic procedural rules. The skill forces the agent to configure includeSource in vitest.config.ts, inject correct ambient typings in vite-env.d.ts, and enforce tree-shaking dead-code elimination (define: { 'import.meta.vitest': 'undefined' }) during production builds.

Prerequisites & Environment Requirements

Codex CLI / Desktop, Claude Code CLI, Cursor IDE, or Windsurf installed
Node.js 20+ / pnpm 9+ installed in the workspace environment
Vitest 1.4+ and Vite 5+ installed as project devDependencies
TypeScript 5+ initialized with a valid tsconfig.json

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install vitest in-source testing in cursor ide#claude code vitest in-source unit testing rules#codex desktop vitest in-source testing setup tutorial#how to fix import.meta.vitest typescript error#deterministic vitest in-source unit testing SOP#vitest in-source testing vite-env.d.ts reference types#vitest in-source testing bundle dead code elimination

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Mount the skill manifest into your agent runtime's global or workspace-level skill registry.

Autonomous agents discover behavioral constraints through YAML-frontmattered markdown files. Place the Vitest In-Source Testing skill in your project's .claude/skills, .cursor/skills, or global ~/.agents/skills directory so the agent's semantic router can match trigger phrases such as 'setup in-source testing vitest'.

Terminal Command
mkdir -p .agents/skills/vitest-in-source-unit-testing && curl -fsSL https://askills.dev/api/skills/vitest-in-source-unit-testing/raw -o .agents/skills/vitest-in-source-unit-testing/SKILL.md
.agents/skills/vitest-in-source-unit-testing/SKILL.md
---
name: "vitest-in-source-unit-testing"
description: "Write unit tests directly alongside implementation code with instant Vite-powered HMR."
metadata:
  author: "Vitest"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "setup in-source testing vitest"
  - "run vitest watch"
  - "benchmark with vitest"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---
Production Pro-Tip

Place the SKILL.md in .cursor/rules or .claude/skills to allow per-repository context injection without polluting other non-Vite projects.

Sandbox Gotcha

Ensure permissions.shell_exec is kept false in the manifest if operating in untrusted sandboxes; allow the agent to edit files while running execution commands manually if strict containment is active.

2

Configuring Vitest & TypeScript Compiler Boundaries

Configure includeSource in vitest.config.ts and register ambient types to eliminate TypeScript compilation failures.

By default, Vitest ignores in-source test blocks. The agent must update vitest.config.ts to scan matching source files and update vite-env.d.ts with the vitest/importMeta reference. Crucially, the production build config must declare import.meta.vitest as undefined so Rollup/Esbuild completely tree-shakes test logic.

Terminal Command
pnpm add -D vitest @vitest/coverage-v8 typescript
vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  define: {
    'import.meta.vitest': 'undefined',
  },
  test: {
    includeSource: ['src/**/*.{js,ts}'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
Production Pro-Tip

Ensure src/vite-env.d.ts includes /// <reference types="vitest/importMeta" /> to give the agent IDE auto-completion for import.meta.vitest without runtime polyfills.

Sandbox Gotcha

If you forget define: { 'import.meta.vitest': 'undefined' }, test blocks and their imported mock assertions will be bundled into production JS artifacts.

3

Intent Matching & In-Source Test Implementation

Direct the autonomous agent to implement functionality and embed tests in the same file using import.meta.vitest.

Invoke the agent using one of the calibrated triggers. The agent evaluates the rule set, constructs the pure domain logic, and appends the test suite inside an if (import.meta.vitest) block at the bottom of the source module, dynamically importing assertions to keep production dependencies decoupled.

src/math/vector.ts
export interface Vector2D {
  x: number;
  y: number;
}

export function addVectors(a: Vector2D, b: Vector2D): Vector2D {
  return { x: a.x + b.x, y: a.y + b.y };
}

// In-source test suite
if (import.meta.vitest) {
  const { it, expect, describe } = import.meta.vitest;

  describe('addVectors', () => {
    it('computes coordinate sum correctly', () => {
      const v1 = { x: 10, y: -5 };
      const v2 = { x: 5, y: 15 };
      expect(addVectors(v1, v2)).toEqual({ x: 15, y: 10 });
    });
  });
}
Production Pro-Tip

Always destructure { it, expect } directly from import.meta.vitest inside the conditional block; never top-level import them from 'vitest'.

Sandbox Gotcha

Avoid top-level heavy mocking libraries or fs modules within in-source testing files; keep in-source tests dedicated to fast pure unit validations.

4

Verification, Coverage Validation & Build Quality Gate

Run test suites and build gates to verify zero production bundle contamination and green tests.

Instruct the agent to execute a dual-gate validation: run Vitest in single-run mode, followed by a production build check to ensure tree-shaking eliminates test code without syntax or type errors.

Terminal Command
npx vitest run --coverage && npx vite build
Production Pro-Tip

Inspect the generated dist/ assets with grep -rn 'computes coordinate sum' dist/ to definitively verify test removal during CI pipeline runs.

Sandbox Gotcha

Check that tsconfig.json contains "types": ["vitest/importMeta"] under compilerOptions if vite-env.d.ts is not automatically picked up by your tsconfig paths.

Real-World Scenario: In-Source Token Bucket Rate Limiter with Vitest Verification

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“setup in-source testing vitest and implement a TokenBucketRateLimiter class in src/security/rateLimiter.ts. Include in-source tests validating burst capacity, refill rates, and replenishment cycles. Ensure tests do not leak into the production bundle.”

Deterministic Agent Verification Pipeline:
Agent inspects vitest.config.ts and tsconfig.json to ensure includeSource and vitest/importMeta typings are present.
Agent creates src/security/rateLimiter.ts containing TokenBucketRateLimiter with private state handling timestamps and capacities.
Agent appends if (import.meta.vitest) { const { it, expect, vi } = import.meta.vitest; ... } at the file footer testing normal acquisition and starvation.
Agent executes npx vitest run src/security/rateLimiter.ts and confirms all unit tests pass with exit code 0.
Agent runs vite build and validates that output bundles exclude rateLimiter test strings.

Runtime Troubleshooting & Failure Modes

Error: Property 'vitest' does not exist on type 'ImportMeta'. TS2339

Root Cause: TypeScript's compiler is unaware of Vitest's custom augmentations to the ES standard ImportMeta interface because the ambient type definitions were not linked.

Resolution Command / Fix:
Add /// <reference types="vitest/importMeta" /> to src/vite-env.d.ts or append "vitest/importMeta" to compilerOptions.types in tsconfig.json.
Error: ReferenceError: describe is not defined (or import.meta.vitest is undefined at runtime)

Root Cause: Tests were invoked using an external runner or Vitest ran without includeSource matching the target path, or test utilities were used globally without being destructured from import.meta.vitest.

Resolution Command / Fix:
Ensure vitest.config.ts has includeSource: ['src/**/*.{js,ts}'] and verify the test block uses: const { describe, it, expect } = import.meta.vitest;

Frequently Asked Questions (Vitest In-Source Unit Testing & Instant ESM Execution SOP)

Q:Can I use Vitest In-Source Unit Testing & Instant ESM Execution across Codex, Claude Code, and Cursor simultaneously?

Yes. This skill adheres strictly to the universal SKILL.md specification. Runtimes like Claude Code, Codex, Cursor, and Windsurf parse the same YAML triggers and execution steps to enforce consistent file generation and testing behaviors.

Q:How does Vitest In-Source Unit Testing prevent context window overflow during long agent sessions?

Traditional unit testing forces agents to load both the source file and an external test file into the LLM context window. In-source testing combines implementation and verification in a single file buffer, reducing context overhead and eliminating stale cross-file references.

Q:Does in-source testing increase the bundle size of my production application?

No. When configured properly with define: { 'import.meta.vitest': 'undefined' } in vitest.config.ts/vite.config.ts, Vite and Rollup treat if (import.meta.vitest) as an unreachable dead-code branch (if (false)) and completely remove it during minification.

Ready to equip your autonomous agent with Vitest In-Source Unit Testing & Instant ESM Execution?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec