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.
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
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
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'.
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---
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
---Place the SKILL.md in .cursor/rules or .claude/skills to allow per-repository context injection without polluting other non-Vite projects.
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.
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.
pnpm add -D vitest @vitest/coverage-v8 typescriptimport { defineConfig } from 'vitest/config';
export default defineConfig({
define: {
'import.meta.vitest': 'undefined',
},
test: {
includeSource: ['src/**/*.{js,ts}'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
},
},
});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.
If you forget define: { 'import.meta.vitest': 'undefined' }, test blocks and their imported mock assertions will be bundled into production JS artifacts.
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.
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 });
});
});
}Always destructure { it, expect } directly from import.meta.vitest inside the conditional block; never top-level import them from 'vitest'.
Avoid top-level heavy mocking libraries or fs modules within in-source testing files; keep in-source tests dedicated to fast pure unit validations.
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.
npx vitest run --coverage && npx vite buildInspect the generated dist/ assets with grep -rn 'computes coordinate sum' dist/ to definitively verify test removal during CI pipeline runs.
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
“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.”
Runtime Troubleshooting & Failure Modes
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.
Add /// <reference types="vitest/importMeta" /> to src/vite-env.d.ts or append "vitest/importMeta" to compilerOptions.types in tsconfig.json.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.
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.