|
| 1 | +import { createMock } from '@golevelup/ts-jest' |
| 2 | +import { CallHandler, ExecutionContext } from '@nestjs/common' |
| 3 | +import { Reflector } from '@nestjs/core' |
| 4 | +import { lastValueFrom, of } from 'rxjs' |
| 5 | +import { z } from 'zod' |
| 6 | +import { createZodDto } from './dto' |
| 7 | +import { ZodSerializerInterceptor } from './serializer' |
| 8 | + |
| 9 | +describe('ZodSerializerInterceptor', () => { |
| 10 | + const UserSchema = z.object({ |
| 11 | + username: z.string(), |
| 12 | + }) |
| 13 | + |
| 14 | + class UserDto extends createZodDto(UserSchema) {} |
| 15 | + |
| 16 | + const testUser = { |
| 17 | + username: 'test', |
| 18 | + password: 'test', |
| 19 | + } |
| 20 | + |
| 21 | + const context = createMock<ExecutionContext>() |
| 22 | + const handler = createMock<CallHandler>({ |
| 23 | + handle: () => of(testUser), |
| 24 | + }) |
| 25 | + |
| 26 | + test('interceptor should strip out password', async () => { |
| 27 | + const reflector = createMock<Reflector>({ |
| 28 | + getAllAndOverride: () => UserDto, |
| 29 | + }) |
| 30 | + |
| 31 | + const interceptor = new ZodSerializerInterceptor(reflector) |
| 32 | + |
| 33 | + const userObservable = interceptor.intercept(context, handler) |
| 34 | + const user: typeof testUser = await lastValueFrom(userObservable) |
| 35 | + |
| 36 | + expect(user.password).toBe(undefined) |
| 37 | + expect(user.username).toBe('test') |
| 38 | + }) |
| 39 | + |
| 40 | + test('interceptor should not strip out password if no UserDto is defined', async () => { |
| 41 | + const context = createMock<ExecutionContext>() |
| 42 | + const handler = createMock<CallHandler>({ |
| 43 | + handle: () => of(testUser), |
| 44 | + }) |
| 45 | + const reflector = createMock<Reflector>({ |
| 46 | + getAllAndOverride: jest.fn(), |
| 47 | + }) |
| 48 | + |
| 49 | + const interceptor = new ZodSerializerInterceptor(reflector) |
| 50 | + |
| 51 | + const userObservable = interceptor.intercept(context, handler) |
| 52 | + const user: typeof testUser = await lastValueFrom(userObservable) |
| 53 | + |
| 54 | + expect(user.password).toBe('test') |
| 55 | + expect(user.username).toBe('test') |
| 56 | + }) |
| 57 | +}) |
0 commit comments