In-Source Testing & Zero-Overhead Production Dead Code Elimination
Embedding unit tests directly inside implementation files and stripping them in production builds.
Part 10 in Series — Catch up on the previous article: Vitest Browser Mode: Executing Tests in Real Chromium, Firefox, and WebKit Engines (Part 9) before diving into this post.
In-source testing lets you write unit tests directly inside the same file as your implementation code, similar to Rust’s #[cfg(test)] modules.
This is especially effective for utility functions, math helpers, and data parsing algorithms where co-locating tests improves developer velocity.
// src/utils/math.ts
export function add(a: number, b: number): number {
return a + b;
}
// In-source test block (only executed when running Vitest)
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
}
Production Dead Code Elimination
To ensure test blocks are stripped from production bundle output, configure Vite’s define replacement:
// vite.config.ts
export default defineConfig({
define: {
'import.meta.vitest': 'undefined',
},
test: {
includeSource: ['src/**/*.{js,ts}'],
},
});
When building for production (vite build), esbuild replaces import.meta.vitest with undefined. The dead-code elimination (tree-shaking) pass removes the if (false) block completely, resulting in zero bytes added to production output.
Part 11: Type-Level Testing: expectTypeOf and Static Type System Assertions
Continue to Part 11 →