与Nestjs,Jest,最多,Prisma和TestContainers进行集成测试
#node #测试 #docker #nestjs

Motiva㧣o

好吧,我没有很多习惯可以做这类出版物,但是由于我发现我日常生活中使用的堆栈没有任何特定的习惯,所以我决定逐步带来此逐步。

我们的API

对于此测试场景,我决定使用Nestjs与Prisma一起创建一个API REST,以执行数据持续存在。

设置进行测试

确保您的母亲在母亲中运行的docker和节点


import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
import {
  PostgreSqlContainer,
  StartedPostgreSqlContainer,
} from '@testcontainers/postgresql';
import { execSync } from 'child_process';
import { AppModule } from 'src/app.module';
import * as request from 'supertest';

describe('test POST /users', () => {
  let prisma: PrismaClient;
  let app: INestApplication;
  let container: StartedPostgreSqlContainer;

 beforeAll(async () => {
    // iniciando o container docker
    container = await new PostgreSqlContainer().start();

    // configurando a URL de conexão do prisma
    const urlConnection = `postgresql://${container.getUsername()}:${container.getPassword()}@${container.getHost()}:${container.getPort()}/${container.getDatabase()}?schema=public`;

    // definir a URL de conexão para conexãp do prisma
    process.env.DATABASE_URL = urlConnection;

    // criar as tabelas definidas no prisma no banco de dados
    execSync('npx prisma db push', {
      env: {
        ...process.env,
        DATABASE_URL: urlConnection,
      },
    });

    // importar o modúlo que queremos testar
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    // criar a aplicação
    app = moduleRef.createNestApplication();

    // Instanciar o prisma client com a URL de conexão
    prisma = new PrismaClient({
      datasources: {
        db: {
          url: urlConnection,
        },
      },
    });

    // Iniciar a aplicação
    await app.init();
  });

已经完成了此操作,我们已经准备好开始测试。 @testContainers/postgresql 库将抽象数据库的所有部分。

测试用例

  it('deve criar um novo usuário', async () => {
    // Act
    const response = await request(await app.getHttpServer())
      .post('/users')
      .send({
        email: 'test@mail.com',
        name: 'John Doe',
      });

    // Assert
    const userDb = await prisma.users.findFirst();
    expect(response.statusCode).toBe(201);
    expect(userDb.email).toBe('test@mail.com');
    expect(userDb.name).toBe('John Doe');
  });

  it('deve lançar um erro porque já existe um usuário com esse email', async () => {
    // Act
    const response = await request(await app.getHttpServer())
      .post('/users')
      .send({
        email: 'test@mail.com',
        name: 'John Doe',
      });

    // Assert
    expect(response.statusCode).toBe(422);
  });

  it('deve lançar um erro porque não foram enviados os dados para criação do usuário', async () => {
    // Act
    const response = await request(await app.getHttpServer()).post('/users');

    // Assert
    expect(response.statusCode).toBe(400);
  });

我们执行所有测试后...

  afterAll(async () => {
    // encerrar o container em execução
    await container.stop();
  });

运行测试

npm run test

我们的航站楼

Image description

容器没有Docker

Image description

链接

Documentaã§o do testContainers para o node: https://node.testcontainers.org/modules/postgresql/

我在github的存储库:
https://github.com/daviArttur/nestjs-testcontainers