Skip to content

Instantly share code, notes, and snippets.

@navjotahuja92
Last active February 2, 2024 15:11
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save navjotahuja92/f51601b17fb248cf4727b5650d945607 to your computer and use it in GitHub Desktop.
Save navjotahuja92/f51601b17fb248cf4727b5650d945607 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;
};
@thisismydesign
Copy link

Thank for the example! Keep in mind that you can also just add a custom TypeOrmModule like so: https://stackoverflow.com/a/66298268/2771889

@LeonManolo
Copy link

Do you have an complete example?

@chungminhtu
Copy link

@grantvanhorn
Copy link

You all are awesome, this helped me a lot.

@theusindabike
Copy link

Same here! Thanks folks!

@doyeka
Copy link

doyeka commented Aug 16, 2023

Huge thanks. Do you mind explaining why you chose { name: 'default', synchronize: true, } for the TypeOrmModuleOptions argument?

I was also trying to inject the provider using { getDataSourceToken } from "@nestjs/typeorm". I wonder why overriding the provider versus injecting it makes a difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment