Skip to content

Commit

Permalink
test(@nestjs/typeorm): add test for connectionFactory
Browse files Browse the repository at this point in the history
Add unit test for async options with connectionFactory.
  • Loading branch information
IRCraziestTaxi committed Jul 7, 2021
1 parent 6295073 commit a9ef5df
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
30 changes: 30 additions & 0 deletions tests/e2e/typeorm-async-connection-factory-options.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AsyncConnectionFactoryOptionsFactoryModule } from '../src/async-connection-factory-options.module';
import { Server } from 'http';

describe('TypeOrm (async configuration with connectionFactory)', () => {
let server: Server;
let app: INestApplication;

beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AsyncConnectionFactoryOptionsFactoryModule],
}).compile();

app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});

it(`should return created entity`, () => {
return request(server)
.post('/photo')
.expect(201, { name: 'Nest', description: 'Is great!', views: 6000 });
});

afterEach(async () => {
await app.close();
});
});
47 changes: 47 additions & 0 deletions tests/src/async-connection-factory-options.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Module } from '@nestjs/common';
import { createConnection } from 'typeorm';
import { TypeOrmModule } from '../../lib';
import { Photo } from './photo/photo.entity';
import { PhotoModule } from './photo/photo.module';

@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: () => ({
type: 'postgres',
host: '0.0.0.0',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [Photo],
synchronize: true,
retryAttempts: 2,
retryDelay: 1000,
}),
connectionFactory: async (options) => {
// Realistically, this function would be used for more than simply creating a connection,
// i.e. checking for an existing and active connection prior to creating a new one.
// However, including that logic here causes runtime test errors about variables being used before assignment.
// Therefore, given the simple nature of this test case, simply create and return a connection.
const connection = await createConnection(options!);
return connection;
},
}),
TypeOrmModule.forRoot({
name: 'connection_2',
type: 'postgres',
host: '0.0.0.0',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [Photo],
synchronize: true,
retryAttempts: 2,
retryDelay: 1000,
}),
PhotoModule,
],
})
export class AsyncConnectionFactoryOptionsFactoryModule {}

0 comments on commit a9ef5df

Please sign in to comment.