Drizzle TeamDT
Drizzle Team•12mo ago
uber

🚨 Issue: Testing with PostgreSQL and Drizzle ORM using Testcontainers

I’m writing tests for a function (listProjects) that interacts with a PostgreSQL database using Drizzle ORM. The problem is that listProjects is using a global db instance, which is initialized in the main application. In my tests, I want to use a PostgreSQL container from Testcontainers to spin up a test database, but my test code ends up using a different db instance, not the one I need.

import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schemas";

// Global db instance
const connection = postgres(process.env.DATABASE_URL);
const db = drizzle(connection, { logger: false, schema });

export default db;


test.ts
import { PostgreSqlContainer } from "@testcontainers/postgresql";
import { drizzle, PostgresJsDatabase } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { beforeAll, afterAll, describe, it, expect } from "vitest";
import { Project } from "../project";

let db: PostgresJsDatabase<typeof schema> & { $client: postgres.Sql<{}> };

beforeAll(async () => {
  const container = await new PostgreSqlContainer().start();

  const connectionString = `postgres://postgres:${process.env.POSTGRES_PASSWORD}@${container.getHost()}:${container.getFirstMappedPort()}/test-db`;

  const client = postgres(connectionString);
  db = drizzle(client, { logger: false, schema });
});

afterAll(async () => {
  await container.stop();
});

describe("listProjects", () => {
  it("should return a list of projects", async () => {
    const result = await Project.listProjects();
    expect(result).toBeInstanceOf(Array);
    expect(result.length).toBeGreaterThan(0);
  });
});

method to be tested.
export async function listProjects() {
    const projects = await db.query.projects.findMany({
      with: {
        service: true,
        client: true,
      },
    });
    return projects;
  }
Was this page helpful?