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
beforeAllinicia un contenedor PostgreSQL real utilizandoPostgreSqlContainer. Luego crea un clientepgconectado al contenedor y configura la tablacustomers. - El bloque
afterAllcierra 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).