diff --git a/apps/web/src/lib/server/db.ts b/apps/web/src/lib/server/db.ts index 2b03d0b..83f6016 100644 --- a/apps/web/src/lib/server/db.ts +++ b/apps/web/src/lib/server/db.ts @@ -28,13 +28,21 @@ function applyDefaultPragmas(instance: any): void { * - En Node (Vite dev SSR): better-sqlite3 */ async function importSqliteDatabase(): Promise { + // En tests, forzar bun:sqlite para evitar mezclar engines con la conexión de tests + const nodeEnv = String(process.env.NODE_ENV || '').toLowerCase(); + if (nodeEnv === 'test') { + const mod: any = await import('bun:sqlite'); + return (mod as any).Database || (mod as any).default || mod; + } + // En desarrollo (Vite SSR), cargar better-sqlite3 vía require de Node para mantener el contexto CJS - if (import.meta.env.DEV) { + if (typeof import.meta !== 'undefined' && (import.meta as any).env?.DEV) { const modModule: any = await import('node:module'); const require = modModule.createRequire(import.meta.url); const mod = require('better-sqlite3'); return (mod as any).default || (mod as any).Database || mod; } + // En producción (Bun en runtime), usar bun:sqlite nativo const mod: any = await import('bun:sqlite'); return (mod as any).Database || (mod as any).default || mod; @@ -163,3 +171,16 @@ export async function getDb(filename: string = 'tasks.db'): Promise { _db = await openDb(filename); return _db; } + +/** + * Cierra y resetea la instancia compartida (útil en tests para evitar manejar + * un descriptor abierto al borrar el archivo de la BD en disco). + */ +export function closeDb(): void { + try { + if (_db && typeof _db.close === 'function') { + _db.close(); + } + } catch {} + _db = null; +} diff --git a/tests/web/api.tasks.complete.reaction.test.ts b/tests/web/api.tasks.complete.reaction.test.ts index 1601b6c..bd1120b 100644 --- a/tests/web/api.tasks.complete.reaction.test.ts +++ b/tests/web/api.tasks.complete.reaction.test.ts @@ -1,5 +1,6 @@ import { beforeEach, afterEach, describe, expect, it } from 'bun:test'; import { createTempDb } from './helpers/db'; +import { closeDb } from '../../apps/web/src/lib/server/db.ts'; import { POST as completeHandler } from '../../apps/web/src/routes/api/tasks/[id]/complete/+server.ts'; function toIsoSql(d: Date): string { @@ -35,6 +36,8 @@ describe('Web API - completar tarea encola reacción ✅', () => { }); afterEach(() => { + // Cerrar la conexión singleton de la web antes de borrar el archivo + try { closeDb(); } catch {} if (cleanup) cleanup(); // Limpiar env relevantes delete process.env.DB_PATH;