Files
lingxi/apps/api/src/common/pipes/zod-validation.pipe.spec.ts
T
Stev_Wang 23067edb8f feat(api): 搭建 API 与 Worker 骨架及契约基线
NestJS 11 + Fastify 统一错误体与 trace_id,/health 真实探活 DB/Redis,OpenAPI 3.1 契约含 20 个错误码;shared 包提供错误码、权限点、ULID、分页与通用 schema;worker 完成队列进程骨架。
2026-11-02 17:20:46 +08:00

40 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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' }],
});
}
});
});