import { Context } from "@src/context" ; import { EntityManager } from "@src/entities" ; import { config } from "dotenv" ; import { PostgresDriver , PostgresDriverOpts , TestUuidAssigner } from "joist-orm" ; import { toMatchEntity } from "joist-test-utils" ; import { newPgConnectionConfig } from "joist-utils" ; import { knex as createKnex , Knex } from "knex" ; if ( process . env . DATABASE_URL === undefined ) { config ( { path : "./local.env" } ) ; } export let knex ; const testUuidAssigner = new TestUuidAssigner ( ) ; beforeEach ( ( ) => testUuidAssigner . reset ( ) ) ; export function newEntityManager ( opts ? ) { const ctx = { knex } ; const em = new EntityManager ( ctx as any , new PostgresDriver ( knex , { idAssigner : testUuidAssigner , ... opts , } ) ) ; Object . assign ( ctx , { em } ) ; return em ; } export let numberOfQueries = 0 ; export let queries = [ ] ; expect . extend ( { toMatchEntity } ) ; beforeAll ( async ( ) => { knex = createKnex ( { client : "pg" , connection : newPgConnectionConfig ( ) , debug : false , asyncStackTraces : true , } ) . on ( "query" , ( e ) => { numberOfQueries ++ ; queries . push ( e . sql ) ; } ) ; } ) ; beforeEach ( async ( ) => { await knex . select ( knex . raw ( "flush_database()" ) ) ; resetQueryCount ( ) ; } ) ; afterAll ( async ( ) => { await knex . destroy ( ) ; } ) ; export function resetQueryCount ( ) { numberOfQueries = 0 ; queries = [ ] ; } type itWithCtxFn = ( ctx : Context ) => Promise < void > ; it . withCtx = ( name , fnOrOpts , maybeFn ? ) => { const fn = typeof fnOrOpts === "function" ? fnOrOpts : maybeFn ! ; it ( name , async ( ) => fn ( { em : newEntityManager ( ) , knex } ) ) ; } ;