What is Database Test Isolation?
Sonamu wraps each test in a transaction and automatically rolls back when the test ends. This ensures:- Data doesnβt mix between tests
- Always same results regardless of test execution order
- No separate cleanup needed to restore DB to initial state
Automatic Transaction Management
bootstrap() Function
Sonamuβsbootstrap() function automatically manages transactions:
What bootstrap() Does
beforeEach: Create transaction before each test startsafterEach: Rollback transaction after each test ends- Always rollback regardless of test success/failure
Test Environment DB Configuration
sonamu.config.ts
Test DB is configured insonamu.config.ts:
- Test DB is completely separate from development/production DB
- Set
pool.max: 1to use single connection (guarantees transaction isolation)
DB Class Test Mode
TheDB class automatically switches to test mode when NODE_ENV=test:
Transaction Isolation Mechanism
createTestTransaction()
Called inbeforeEach to start a new transaction:
- Get Write DB instance
- Start new transaction
- Store in
testTransactionproperty - All subsequent queries execute through this transaction
clearTestTransaction()
Called inafterEach to rollback and clean up transaction:
- Rollback current transaction (cancel all changes)
- Initialize
testTransactiontonull - Ready for next test
Practical Examples
Basic CRUD Test
Multiple Table Operations
Error Handling in Transactions
Complex Business Logic Test
Test Isolation Verification
Isolation Check Test
Manual Transaction Control
You can manually control transactions when needed:Operations Outside Transaction (Caution)
Some operations execute outside transaction scope, so caution is needed:File System Mocking
Use Naite Mock for file operations:Performance Optimization
Single Connection Pool
In test environment, setpool.max: 1 to use only single connection:
- Same connection must be used to guarantee transaction isolation
- Transactions arenβt shared with multiple connections
Limit Parallel Execution
Running tests sequentially is safer:vitest.config.ts: