概要
前回はテストコード中にpgを使ってテーブルの初期設定を行った。
今回はDrizzleのマイグレーションを使ってテーブルの初期設定を行う。
ソース
pps/backend/test/integration.spec.ts
// 省略
beforeAll(async () => {
// PostgreSQLコンテナを起動
postgresContainer = await new PostgreSqlContainer('postgres:17.4-alpine')
.withDatabase('test_db')
.withUsername('test_user')
.withPassword('test_password')
.start();
connectionString = postgresContainer.getConnectionUri();
+ await setupDb(connectionString);
+ await execSql(
+ connectionString,
+ `
+ INSERT INTO odyssage.users (id, name) VALUES ('${testUserId}', '${testUserName}');
+ INSERT INTO odyssage.scenarios (id, title, user_id, updated_at) VALUES ('${testScenarioId}', '${testScenarioTitle}', '${testUserId}', CURRENT_TIMESTAMP)
+ `,
+ );
// アプリを初期化
app = new Hono();
app.route('/api/sessions', sessionRoute);
}, 60000); // コンテナ起動に時間がかかるためタイムアウトを延長
// テスト終了後にコンテナを停止
afterAll(async () => {
await postgresContainer.stop();
});
// 省略
packages/database/test-utils/setupDb.ts
import * as path from 'path';
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
export async function setupDb(connectionString: string) {
const db = drizzle(connectionString);
await migrate(db, {
migrationsFolder: path.join(__dirname, '../migrations'), // drizzle.config.tsで指定したものと同じ
});
}
packages/database/test-utils/execSql.ts
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
export async function execSql(connectionString: string, sqlText: string) {
const db = drizzle(connectionString);
await db.execute(sql.raw(sqlText));
}
参考
drizzle-orm
使い捨てテストDB環境のtestcontainersをPostgresql + Honoで試してみたメモ
Drizzle ORM でダミーデータを流し込む方法
postgres