import { ErrorCode } from '@lingxi/shared'; import { describe, expect, it } from 'vitest'; import { z } from 'zod'; import { AppException } from '../errors/app-exception'; import { ZodValidationPipe } from './zod-validation.pipe'; const schema = z.object({ name: z.string().min(2), limit: z.coerce.number().int().min(1).max(100).default(20), }); describe('ZodValidationPipe', () => { it('通过校验并返回转换后的值', () => { const pipe = new ZodValidationPipe(schema); expect(pipe.transform({ name: '素材', limit: '30' })).toEqual({ name: '素材', limit: 30 }); }); it('缺省值生效', () => { const pipe = new ZodValidationPipe(schema); expect(pipe.transform({ name: '素材' })).toEqual({ name: '素材', limit: 20 }); }); it('校验失败抛 40001,details 带字段错误', () => { const pipe = new ZodValidationPipe(schema); try { pipe.transform({ name: 'x' }); throw new Error('应当抛错'); } catch (error) { expect(error).toBeInstanceOf(AppException); const appError = error instanceof AppException ? error : null; expect(appError?.code).toBe(ErrorCode.PARAM_INVALID); expect(appError?.status).toBe(400); expect(appError?.details).toMatchObject({ issues: [{ path: 'name' }], }); } }); });