首頁  >  文章  >  web前端  >  使用 NestJS、TypeORM 和 PostgreSQL 在真實資料庫中建立測試

使用 NestJS、TypeORM 和 PostgreSQL 在真實資料庫中建立測試

Barbara Streisand
Barbara Streisand原創
2024-10-04 12:17:30131瀏覽

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