首页 > web前端 > js教程 > 正文

使用 NestJS、TypeORM 和 PostgreSQL 在真实数据库中创建测试

Barbara Streisand
发布: 2024-10-04 12:17:30
原创
131 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!