Nest container 없이 순수 Service 규칙의 경계값을 검증합니다.
의존성이 없는 업무 규칙은 일반 class로 빠르게 테스트하고, provider wiring이 필요한 경우 TestingModule로 실제 Nest 구성을 검증합니다.
정상값뿐 아니라 0, 최대값, 범위 밖 값과 예상 예외를 검사합니다.
Controller e2e 테스트는 HTTP status, validation, auth와 응답 schema를 확인하고 외부 시스템은 통제된 대역을 사용합니다.
구현 내부 private 호출 횟수만 검사하면 리팩터링에 취약하고 업무 계약을 놓칩니다.
로컬 프로젝트에서 확인해보세요discount 100과 101 경계 테스트를 추가하세요.
import "reflect-metadata";
import { Controller, Get, Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
class PriceService {
discount(price: number, rate: number) {
if (price < 0 || rate < 0 || rate > 100) throw new RangeError("잘못된 범위");
return (price * (100 - rate)) / 100;
}
}
function test(name: string, run: () => void) {
try {
run();
return { name, passed: true };
} catch (error) {
return { name, passed: false, error: (error as Error).message };
}
}
@Controller()
class AppController {
@Get() home() {
const service = new PriceService();
return [
test("10% 할인", () => {
if (service.discount(10000, 10) !== 9000) throw new Error("기대값 불일치");
}),
test("음수 거절", () => {
try {
service.discount(-1, 10);
throw new Error("예외 없음");
} catch (e) {
if (!(e instanceof RangeError)) throw e;
}
}),
];
}
}
@Module({ controllers: [AppController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(4173, "0.0.0.0");
}
bootstrap();