70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
import 'reflect-metadata';
|
|
import {
|
|
DatabaseService,
|
|
utcDatabaseUrl,
|
|
} from '../src/database/database.service';
|
|
import { parseEnvironment } from '../src/config/environment';
|
|
|
|
describe('database lifecycle', () => {
|
|
it('preserves credentials and other startup options while enforcing UTC last', () => {
|
|
const source = new URL(
|
|
'postgresql://user:p%40ss@localhost/mani?sslmode=require',
|
|
);
|
|
source.searchParams.set(
|
|
'options',
|
|
'-c application_name=mani -c timezone=Asia/Kolkata',
|
|
);
|
|
const result = new URL(utcDatabaseUrl(source.toString()));
|
|
expect(result.username).toBe(source.username);
|
|
expect(result.password).toBe(source.password);
|
|
expect(result.searchParams.get('sslmode')).toBe('require');
|
|
expect(result.searchParams.get('options')).toBe(
|
|
'-c application_name=mani -c timezone=Asia/Kolkata -c timezone=UTC',
|
|
);
|
|
expect(
|
|
new URL(utcDatabaseUrl('postgresql://localhost/mani')).searchParams.get(
|
|
'options',
|
|
),
|
|
).toBe('-c timezone=UTC');
|
|
expect(
|
|
new URL(
|
|
utcDatabaseUrl(
|
|
'postgresql://localhost/mani',
|
|
'-c application_name=env',
|
|
),
|
|
).searchParams.get('options'),
|
|
).toBe('-c application_name=env -c timezone=UTC');
|
|
});
|
|
let database: DatabaseService;
|
|
beforeEach(() => {
|
|
database = new DatabaseService(
|
|
parseEnvironment({ DATABASE_URL: 'postgresql://localhost/mani' }),
|
|
);
|
|
});
|
|
it('connects during initialization', async () => {
|
|
const connect = jest.spyOn(database, '$connect').mockResolvedValue();
|
|
await database.onModuleInit();
|
|
expect(connect).toHaveBeenCalledTimes(1);
|
|
});
|
|
it('disconnects during shutdown', async () => {
|
|
const disconnect = jest.spyOn(database, '$disconnect').mockResolvedValue();
|
|
await database.onModuleDestroy();
|
|
expect(disconnect).toHaveBeenCalledTimes(1);
|
|
});
|
|
it('propagates connection failures', async () => {
|
|
jest
|
|
.spyOn(database, '$connect')
|
|
.mockRejectedValue(new Error('unavailable'));
|
|
await expect(database.onModuleInit()).rejects.toThrow('unavailable');
|
|
});
|
|
it('executes a database probe and propagates query failure', async () => {
|
|
const query = jest
|
|
.spyOn(database, '$queryRaw')
|
|
.mockResolvedValue([{ value: 1 }]);
|
|
await database.ping();
|
|
expect(query).toHaveBeenCalledTimes(1);
|
|
query.mockRejectedValue(new Error('timeout'));
|
|
await expect(database.ping()).rejects.toThrow('timeout');
|
|
});
|
|
});
|