Skip to content

Instantly share code, notes, and snippets.

@a-h-i
Forked from navjotahuja92/setup.ts
Created July 7, 2022 11:02
Show Gist options
  • Save a-h-i/2526abf9c2db7d7fb5095e3725208e63 to your computer and use it in GitHub Desktop.
Save a-h-i/2526abf9c2db7d7fb5095e3725208e63 to your computer and use it in GitHub Desktop.
Nest.js Test Setup with In Memory Postgres Database (pg-mem)
// 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;
};
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