@Post('path')
@UseGuards(JwtAuthGuard)
@HttpCode(201)
postRoutine(@Body() saveRoutines: SaveRoutinesRequestDto, @Request() req: any) {
return this.routineService.bulkInsertRoutines(req.user, saveRoutines);
}

 

주어진 코드에서 데코레이션이 정확하게 작동하는지 테스트하는 방법은

Reflect.getMetadata(metadataKey, target) 를 사용하면 된다.

 

사용방법

 

@UseGaurds(JwtAuthGuard)

import {JwtAuthGuard} from '../common/jwtPassport/'
import {GUARDS_METADATA} from '@nestjs/common/constants';

const guards = Reflect.getMetadata(GUARDS_METADATA, controller.postRoutine);
expect(guards[0]).toBe(JwtAuthGuard);
  • __guards__   NestJS에서 @UseGuards() 데코레이터를 사용하면, 해당 메서드에 가드가 설정됩니다. 이 정보는 __guards__라는 메타데이터 키로 저장됩니다.
  • __guards__ 를 이용해서 postRoutine 에서 사용된 @UseGaurds(JwtAuthGuard) 의 동작여부 확인

@HttpCode(201)

import {HTTP_CODE_METADATA} from '@nestjs/common/constants';

const httpCode = Reflect.getMetadata(HTTP_CODE_METADATA, controller.postRoutine);
expect(httpCode).toBe(201);
  • __httpCode__ : NestJS에서 @HttpCode() 데코레이터를 사용하면, 해당 메서드의 http 상태 코드가 설정됩니다.이 정보는 __httpCode__라는 메타데이터키로 저장됩니다.
  • __httpCode__ 를 이용해서 postRoutine 에서 사용된 @HttpCode(201) 의 동작여부를 확인

const path = Reflect.getMetadata(ROUTE_METADATA, controller.getAllRoutineByUser); const method = Reflect.getMetadata(METHOD_METADATA, controller.getAllRoutineByUser);

 

@Post('path')

import { PATH_METADATA, METHOD_METADATA } from '@nestjs/common/constants';
import { RequestMethod } from '@nestjs/common';


const path = Reflect.getMetadata(PATH_METADATA, controller.postRoutine);
const method = Reflect.getMetadata(METHOD_METADATA, controller.postRoutine);

expect(method).toBe(RequestMethod.POST);
expect(path).toBe('path');
  • METHOD_METADATA =  NestJS에서 HTTP 메서드를 나타내는 상수로, RequestMethod 열거형(enum) 값을 반환
export enum RequestMethod {
  GET = 0,
  POST = 1,
  PUT = 2,
  DELETE = 3,
  PATCH = 4,
  ALL = 5,
  OPTIONS = 6,
  HEAD = 7,
}

 

+ Recent posts