개발 속도가 다소 느려질 수 있다.
Controller Layer로 이동하기:
컨트롤러의 엔드포인트와 연관된 통합 테스트를 작성합니다.
이를 통해 엔드포인트가 예상대로 응답하는지, 서비스와 올바르게 연동되는지 확인합니다.
E2E Tests 작성하기:
애플리케이션의 전체 흐름에 대한 테스트를 작성합니다.
이 단계에서는 데이터베이스 연결 등 외부 의존성과의 연동도 함께 테스트합니다.
//Service Layer
// createProduct() => 제품 생성 시 데이터베이스에 제품이 잘 저장되는지 확인
describe('ProductsService', () => {
let service: ProductsService;
let mockRepository = {
create: jest.fn(),
save: jest.fn(),
};
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
ProductsService,
{ provide: getRepositoryToken(Product), useValue: mockRepository },
],
}).compile();
service = module.get<ProductsService>(ProductsService);
});
it('should create a product', async () => {
const productDto = {
name: 'Test Product',
price: 100,
details: 'Details about the product',
// ... other fields
};
mockRepository.create.mockReturnValue(productDto);
mockRepository.save.mockResolvedValue(productDto);
const result = await service.createProduct(productDto);
expect(result).toEqual(productDto);
});
});
//Contoller Layer
// createProduct() => HTTP 요청을 통해 제품이 잘 생성되는지 확인
describe('ProductsController', () => {
let controller: ProductsController;
let mockService = {
createProduct: jest.fn(),
};
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [ProductsController],
providers: [
{ provide: ProductsService, useValue: mockService },
],
}).compile();
controller = module.get<ProductsController>(ProductsController);
});
it('should create a product', async () => {
const productDto = {
name: 'Test Product',
price: 100,
details: 'Details about the product',
// ... other fields
};
mockService.createProduct.mockResolvedValue(productDto);
const result = await controller.createProduct(productDto);
expect(result).toEqual(productDto);
});
});
//Products E2E Test
// createProduct() => 전체 흐름을 테스트하여 제품이 잘 생성되는지 확인.
describe('Products (e2e)', () => {
let app;
beforeEach(async () => {
const moduleFixture = await Test.createTestingModule({
imports: [AppModule], // Make sure AppModule imports everything necessary
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/products (POST)', () => {
return request(app.getHttpServer())
.post('/products')
.send({
name: 'Test Product',
price: 100,
details: 'Details about the product',
// ... other fields
})
.expect(201)
.expect({
id: expect.any(Number),
name: 'Test Product',
price: 100,
details: 'Details about the product',
// ... other fields
});
});
});
describe(): Jest에서 테스트를 그룹화하는 함수입니다. 첫 번째 인자로는 그룹명, 두 번째 인자로는 해당 그룹의 테스트들을 정의하는 함수가 들어갑니다.
beforeEach(): 각 테스트 케이스 실행 전에 매번 실행되는 함수입니다. 여기서는 각 테스트가 시작되기 전에 ProductService 인스턴스를 새로 생성해줍니다.
it() / test(): 실제 테스트 케이스를 정의하는 함수입니다. 첫 번째 인자는 테스트 케이스의 설명, 두 번째 인자는 테스트 로직을 담은 함수가 들어갑니다.
expect(): Jest의 assertion 함수입니다. 여기서는 생성된 상품의 id가 존재하는지, 이름과 가격이 올바른지 확인하고 있습니다.