134 lines
3.5 KiB
TypeScript
134 lines
3.5 KiB
TypeScript
/**
|
|
* Automatic Zod validation setup for test runs
|
|
* This file sets up global hooks that automatically validate all Zod schemas during testing
|
|
*/
|
|
|
|
import { beforeAll, afterAll } from 'vitest';
|
|
import { z } from 'zod';
|
|
|
|
// Store original Zod parse methods
|
|
const originalParse = z.ZodType.prototype.parse;
|
|
const originalSafeParse = z.ZodType.prototype.safeParse;
|
|
|
|
let validationCount = 0;
|
|
let validationErrors: string[] = [];
|
|
|
|
/**
|
|
* Enhanced parse method that logs validation attempts during tests
|
|
* @param data - The data to validate against the schema
|
|
* @returns The parsed and validated data
|
|
*/
|
|
function enhancedParse<T>(this: z.ZodType<T>, data: unknown): T {
|
|
try {
|
|
const result = originalParse.call(this, data);
|
|
validationCount++;
|
|
|
|
// Log successful validations in test mode
|
|
if (process.env.NODE_ENV === 'test') {
|
|
console.log(`✅ Zod validation passed (${validationCount} total)`);
|
|
}
|
|
|
|
return result;
|
|
} catch (error) {
|
|
validationErrors.push(`Zod validation failed: ${error}`);
|
|
|
|
// Log failed validations in test mode
|
|
if (process.env.NODE_ENV === 'test') {
|
|
console.error(`❌ Zod validation failed:`, error);
|
|
}
|
|
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Enhanced safeParse method that logs validation attempts during tests
|
|
* @param data - The data to validate against the schema
|
|
* @returns Safe parse result with success flag and data or error
|
|
*/
|
|
function enhancedSafeParse<T>(
|
|
this: z.ZodType<T>,
|
|
data: unknown
|
|
): z.SafeParseReturnType<unknown, T> {
|
|
const result = originalSafeParse.call(this, data);
|
|
validationCount++;
|
|
|
|
if (process.env.NODE_ENV === 'test') {
|
|
if (result.success) {
|
|
console.log(`✅ Zod safe validation passed (${validationCount} total)`);
|
|
} else {
|
|
console.warn(`⚠️ Zod safe validation failed but was handled gracefully`);
|
|
validationErrors.push(`Zod safe validation failed: ${result.error.message}`);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Install automatic Zod validation hooks for testing
|
|
*/
|
|
export function installZodTestHooks(): void {
|
|
// Replace Zod's parse methods with enhanced versions
|
|
z.ZodType.prototype.parse = enhancedParse;
|
|
z.ZodType.prototype.safeParse = enhancedSafeParse;
|
|
|
|
// Enable global auto-validation flag
|
|
(globalThis as any).__AUTO_VALIDATE__ = true;
|
|
|
|
console.log('🛡️ Automatic Zod validation hooks installed for test run');
|
|
}
|
|
|
|
/**
|
|
* Remove automatic Zod validation hooks
|
|
*/
|
|
export function uninstallZodTestHooks(): void {
|
|
// Restore original methods
|
|
z.ZodType.prototype.parse = originalParse;
|
|
z.ZodType.prototype.safeParse = originalSafeParse;
|
|
|
|
// Disable global auto-validation flag
|
|
(globalThis as any).__AUTO_VALIDATE__ = false;
|
|
|
|
console.log('🔧 Zod validation hooks removed');
|
|
}
|
|
|
|
/**
|
|
* Get validation statistics for test reporting
|
|
* @returns Object containing validation count and errors
|
|
*/
|
|
export function getValidationStats(): {
|
|
count: number;
|
|
errors: string[];
|
|
} {
|
|
return {
|
|
count: validationCount,
|
|
errors: [...validationErrors],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reset validation statistics
|
|
*/
|
|
export function resetValidationStats(): void {
|
|
validationCount = 0;
|
|
validationErrors = [];
|
|
}
|
|
|
|
// Automatic setup for Vitest
|
|
beforeAll(() => {
|
|
installZodTestHooks();
|
|
resetValidationStats();
|
|
});
|
|
|
|
afterAll(() => {
|
|
const stats = getValidationStats();
|
|
console.log(`📊 Test run completed with ${stats.count} Zod validations`);
|
|
|
|
if (stats.errors.length > 0) {
|
|
console.warn(`⚠️ ${stats.errors.length} validation errors encountered during tests`);
|
|
}
|
|
|
|
uninstallZodTestHooks();
|
|
});
|