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
Connection settings come fromSONAMU_DB_* environment variables, not from sonamu.config.ts. With NODE_ENV=test, Sonamu reads .env.test and uses the test preset. If SONAMU_DB_NAME is not set, the database name is <projectName>_test. Shared Knex options such as the pool go in database.defaultOptions.
- The test DB is completely separate from the development and production DBs
database.nameanddatabase.environmentswere removed; Sonamu throws if they are set
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:
Cautions
Next Steps
runWithMockContext
Testing with Mock Context
API Mocking
Mocking external API calls
Naite Logging
Recording and tracking test logs
Bootstrap
Test environment initialization