Drizzle TeamDT
Drizzle Team•3y ago
petja

Mocking database

I want to mock the PostgreSQL database and access it with Drizzle ORM. I tried to write a TypeScript class that should work the same way as pg's Pool class, but instead of hitting an actual database, returns rows from an in-memory object. However when SELECT'ing from the table I had mocked, Drizzle returned an object with all keys having undefined values.

Any help? 🙂

export class MockPool {
  private mocks: Record<string, (params: any[]) => Record<string, any>[]> = {};

  mockQuery(query: string, rows: (params: any[]) => Record<string, any>[]) {
    this.mocks[query] = rows;
  }

  async query(
    query: string | QueryConfig,
    values?: any[]
  ): Promise<Partial<QueryResult>> {
    let queryConfig: QueryConfig;

    if (typeof query === "string") {
      queryConfig = { text: query, values };
    } else {
      queryConfig = { ...query };

      if (values) {
        queryConfig.values = values;
      }
    }

    const mock = this.mocks[queryConfig.text];

    if (!mock) {
      throw new Error(`Missing mock for query ${queryConfig.text}`);
    }

    const rows = mock(queryConfig.values ?? []);

    return {
      rowCount: rows.length,
      rows,
    };
  }
}


Using the mock pool:
import { drizzle } from "drizzle-orm/node-postgres";
const pool = new MockPool()
const db = drizzle(pool as any) // any, because we're not implementing whole Pool class

pool.mock('SELECT * FROM users', () => [{ id: '1234', name: 'Petja' }])

usersTable.select() // { id: undefined, name: undefined }
Was this page helpful?