Last active
February 12, 2025 10:06
-
-
Save navjotahuja92/f51601b17fb248cf4727b5650d945607 to your computer and use it in GitHub Desktop.
Nest.js Test Setup with In Memory Postgres Database (pg-mem)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Install npm i pg-mem --save-dev | |
import { DataSource, Repository } from 'typeorm'; | |
import { newDb, DataType } from 'pg-mem'; | |
import { v4 } from 'uuid'; | |
const setupDataSource = async () => { | |
const db = newDb({ | |
autoCreateForeignKeyIndices: true, | |
}); | |
db.public.registerFunction({ | |
implementation: () => 'test', | |
name: 'current_database', | |
}); | |
db.registerExtension('uuid-ossp', (schema) => { | |
schema.registerFunction({ | |
name: 'uuid_generate_v4', | |
returns: DataType.uuid, | |
implementation: v4, | |
impure: true, | |
}); | |
}); | |
const ds: DataSource = await db.adapters.createTypeormDataSource({ | |
type: 'postgres', | |
entities: [__dirname + '/../../src/**/*.entity{.ts,.js}'], | |
}); | |
await ds.initialize(); | |
await ds.synchronize(); | |
return ds; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const buildTestingModule = async () => { | |
if (testingModule) { | |
return testingModule; | |
} | |
const dataSource = await setupDataSource(); | |
testingModule = await Test.createTestingModule({ | |
imports: [ | |
TypeOrmModule.forRoot({ | |
name: 'default', | |
synchronize: true, | |
}), | |
CoreModule, | |
], | |
}) | |
.overrideProvider(DataSource) | |
.useValue(dataSource) | |
.compile(); | |
return testingModule; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This work for me