|
1 | 1 | import { Body, Controller, INestApplication, Module, Post } from '@nestjs/common'; |
2 | 2 | import { Test } from '@nestjs/testing'; |
3 | 3 |
|
4 | | -import { classToPlain, Exclude, Expose, plainToClass, Type } from 'class-transformer'; |
| 4 | +import { classToPlain, Exclude, Expose, plainToClass, Transform, Type } from 'class-transformer'; |
5 | 5 | import { IsInt, IsString, Max, Min, validate } from 'class-validator'; |
6 | 6 | import { ApiProperty, DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; |
7 | 7 | import { ReferenceObject, SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface'; |
@@ -350,6 +350,54 @@ describe('Integration tests', () => { |
350 | 350 | expect(raw).toEqual({ name: ins.name }); |
351 | 351 | }); |
352 | 352 | }); // END @Expose() & @Exclude() together |
| 353 | + |
| 354 | + describe(`@${ Transform.name }() decorators`, () => { |
| 355 | + describe('Copying @Transform() decorators from an Entity to a DTO.', () => { |
| 356 | + it('Should copy PLAIN_TO_CLASS decorators', () => { |
| 357 | + // arrange |
| 358 | + const date = new Date(); |
| 359 | + class User { |
| 360 | + @Transform(({ value }) => new Date(value)) |
| 361 | + public createdAt!: Date; |
| 362 | + } |
| 363 | + @ApiEntityRef(User) |
| 364 | + class UserCreateDto { |
| 365 | + @ApiPropertyRef() |
| 366 | + public createdAt!: Date; |
| 367 | + } |
| 368 | + const raw = { createdAt: date.toISOString() }; |
| 369 | + |
| 370 | + // act |
| 371 | + const ins = plainToClass(UserCreateDto, raw); |
| 372 | + |
| 373 | + // assert |
| 374 | + expect(ins.createdAt).toBeInstanceOf(Date); |
| 375 | + expect(ins.createdAt.toISOString()).toEqual(date.toISOString()); |
| 376 | + }); |
| 377 | + |
| 378 | + it('Should copy CLASS_TO_PLAIN decorators', () => { |
| 379 | + // arrange |
| 380 | + const date = new Date(); |
| 381 | + class User { |
| 382 | + @Transform(({ value }) => (value as Date).toISOString(), { toPlainOnly: true }) |
| 383 | + public createdAt!: Date; |
| 384 | + } |
| 385 | + @ApiEntityRef(User) |
| 386 | + class UserCreateDto { |
| 387 | + @ApiPropertyRef() |
| 388 | + public createdAt!: Date; |
| 389 | + } |
| 390 | + const ins = new UserCreateDto(); |
| 391 | + ins.createdAt = date; |
| 392 | + |
| 393 | + // act |
| 394 | + const raw = classToPlain(ins); |
| 395 | + |
| 396 | + // assert |
| 397 | + expect(raw).toEqual({ createdAt: date.toISOString() }); |
| 398 | + }); |
| 399 | + }); |
| 400 | + }); // END @${ Transform.name }() decorators |
353 | 401 | }); |
354 | 402 | }); |
355 | 403 | }); |
0 commit comments