import { describe, it, expect } from 'vitest'; import { z } from 'zod'; import { validate } from '../../src/middleware/validate.js'; import { AppError } from '../../src/lib/errors.js'; function runValidate(schema: z.ZodTypeAny, source: 'body' | 'query', data: unknown) { const req = { [source]: data } as Record; let nextArg: unknown; let nextCalled = false; const next = (e?: unknown) => { nextCalled = true; nextArg = e; }; validate(schema, source)(req as never, {} as never, next as never); return { req, nextArg, nextCalled }; } const schema = z.object({ name: z.string().min(1), age: z.number().int().min(10).max(100), }); describe('validate middleware', () => { it('passes valid body and replaces it with parsed data', () => { const { req, nextArg } = runValidate(schema, 'body', { name: 'Jan', age: 30 }); expect(nextArg).toBeUndefined(); expect(req.body).toEqual({ name: 'Jan', age: 30 }); }); it('strips unknown keys (zod object behavior)', () => { const { req } = runValidate(schema, 'body', { name: 'Jan', age: 30, extra: 'x' }); expect(req.body).toEqual({ name: 'Jan', age: 30 }); }); it('rejects invalid body with a 400 AppError carrying zod details', () => { const { nextArg } = runValidate(schema, 'body', { name: '', age: 'x' }); expect(nextArg).toBeInstanceOf(AppError); const err = nextArg as AppError; expect(err.status).toBe(400); expect(err.code).toBe('BAD_REQUEST'); expect(err.details).toHaveProperty('fieldErrors'); }); it('validates query source', () => { const { req, nextArg } = runValidate(z.object({ q: z.string().optional() }), 'query', { q: 'abc', }); expect(nextArg).toBeUndefined(); expect(req.query).toEqual({ q: 'abc' }); }); it('rejects invalid query', () => { const { nextArg } = runValidate(z.object({ q: z.string() }), 'query', {}); expect(nextArg).toBeInstanceOf(AppError); expect((nextArg as AppError).status).toBe(400); }); });