Compartir comentarios
Las respuestas se generan en base a la documentación.

Escribe pruebas con Testcontainers


Crea src/customer-repository.test.js con la prueba:

const { Client } = require("pg");
const { PostgreSqlContainer } = require("@testcontainers/postgresql");
const {
  createCustomerTable,
  createCustomer,
  getCustomers,
} = require("./customer-repository");

describe("Customer Repository", () => {
  jest.setTimeout(60000);

  let postgresContainer;
  let postgresClient;

  beforeAll(async () => {
    postgresContainer = await new PostgreSqlContainer().start();
    postgresClient = new Client({
      connectionString: postgresContainer.getConnectionUri(),
    });
    await postgresClient.connect();
    await createCustomerTable(postgresClient);
  });

  afterAll(async () => {
    await postgresClient.end();
    await postgresContainer.stop();
  });

  it("should create and return multiple customers", async () => {
    const customer1 = { id: 1, name: "John Doe" };
    const customer2 = { id: 2, name: "Jane Doe" };

    await createCustomer(postgresClient, customer1);
    await createCustomer(postgresClient, customer2);

    const customers = await getCustomers(postgresClient);
    expect(customers).toEqual([customer1, customer2]);
  });
});

Esto es lo que hace la prueba:

  • El bloque beforeAll inicia un contenedor PostgreSQL real utilizando PostgreSqlContainer. Luego crea un cliente pg conectado al contenedor y configura la tabla customers.
  • El bloque afterAll cierra la conexión del cliente y detiene el contenedor.
  • La prueba inserta dos clientes, obtiene todos los clientes y verifica que los resultados coincidan.

El tiempo de espera (timeout) de la prueba se establece en 60 segundos para dar tiempo a que el contenedor se inicie en la primera ejecución (cuando es necesario descargar la imagen Docker).