>  기사  >  웹 프론트엔드  >  NestJS, TypeORM 및 PostgreSQL을 사용하여 실제 데이터베이스에서 테스트 만들기

NestJS, TypeORM 및 PostgreSQL을 사용하여 실제 데이터베이스에서 테스트 만들기

Barbara Streisand
Barbara Streisand원래의
2024-10-04 12:17:30132검색

Creating tests in real database with NestJS, TypeORM and PostgreSQL

소개
테스트 기반 개발 모드에 있든 없든 테스트 작성에는 몇 가지 유용한 이점이 있습니다.
이는 개발자가 자신있게 변경하고, 새로운 기능을 추가하고, 테스트를 통해 기능이 그대로 유지되는지 확인하는 코드를 리팩터링할 수 있는 안전망을 제공합니다.

아픔
우리 중 일부는 고급 CPU를 사용하지 못하며 대규모 프로젝트를 처리할 때 특히 좌절감을 느낄 수는 없습니다.
최근에 저는 대규모 NestJS 앱에서 작업 중이었고 일부 TypeORM 쿼리를 테스트하고 싶었고 수정할 때마다 전체 프로젝트를 로드해야 했습니다. 답답한 표정을 떠올려보세요. 저였습니다.

솔루션
테스트를 작성하는 것은 좋은 습관입니다. 그렇죠? 더 빠르게 개발하고 간접적으로 테스트를 생성할 수 있고 모의 객체와 스텁을 생성할 필요가 없다면 어떻게 될까요? 그때 저는 '실제 데이터베이스에 대한 테스트는 아니다'라고 생각했습니다.

코드

테스트 내용은 다음과 같습니다.


import * as dotenv from 'dotenv';
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm'; 
dotenv.config();
describe('Queryes only test', () => {
    let app: INestApplication;
    let foodRepo: FoodRepository;

    beforeAll(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [
                TypeOrmModule.forRootAsync({
                    useFactory: (configService: any) => ({
                        type: 'postgres',

                        host: process.env.TYPEORM_HOST,
                        port: Number(process.env.TYPEORM_PORT),
                        username: process.env.TYPEORM_USERNAME,
                        password: process.env.TYPEORM_PASSWORD,
                        database: process.env.TYPEORM_DATABASE,

                        entities: ['src/app/**/entities/*.entity.*'],
                        synchronize: false,
                        logging: true /* That will make the sql queryes appear in the console */
                    })
                }),
                TypeOrmModule.forFeature([FoodRepository])
            ]
        }).compile();

        app = moduleFixture.createNestApplication();
        await app.init();

        foodRepo = moduleFixture.get<FoodRepository>(FoodRepository);
    });

    jest.setTimeout(30000);

    it('Must find foods from regular customers', async () => {
        const foodsFromRegularCustomers = await foodRepo.findFoodsFromRegularCustomers().getMany();
        expect(Array.isArray(foodsFromRegularCustomers)).toBeTruthy();
    });

    afterAll(async () => {
        await app.close();
    });
});



저게 내 저장소입니다.


async findFoodsFromRegularCustomers() {
  const currentDate = new Date();
  const startOfWeek = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay()));

  return this.createQueryBuilder('food')
    .innerJoin('food.customer', 'customer')
    .innerJoin('customer.orders', 'orders')
    .select([
      'customer.id', 
      'customer.name', 
      'customer.cpf', 
      'customer.address'
    ])
    .where('orders.createdAt >= :startOfWeek', { startOfWeek })
    .groupBy('customer.id')
    .having('COUNT(orders.id) > :minOrders', { minOrders: 10 })  
}



그 테스트가 완벽할 수는 없지만 장담합니다.
이는 개발자 팀이 잘못된 쿼리를 보내는 것을 방지하는 데 도움이 됩니다.

customer.address와 같은 일부 엔터티 속성이나 관계가 존재하지 않는 경우에도 쿼리 빌더는빌드 시간에 중단되지 않습니다. 하지만 테스트는 그럴 것입니다.?

위 내용은 NestJS, TypeORM 및 PostgreSQL을 사용하여 실제 데이터베이스에서 테스트 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.