What is runWithMockContext?
runWithMockContext is a function that provides isolated Context in Sonamuβs test environment. Sonamu uses AsyncLocalStorage to maintain independent Context per request, and the same mechanism is used in tests.Context Components
Mock Context includes the following properties:Basic Usage
Regular Tests (Unauthenticated)
Sonamuβstest() function automatically runs runWithMockContext.
Direct Usage
You can also callrunWithMockContext directly:
Testing as Authenticated User
Using testAs()
UsetestAs() to simulate logged-in state as a specific user:
Type Safety
testAs() supports generics for type safety:
Practical Examples
Model Method Test
Permission Verification Test
Context Property Manipulation
You can modify Context properties to test specific scenarios:test() vs testAs() Comparison
- test()
- testAs()
Unauthenticated testWhen to use:
- Testing public APIs that donβt require authentication
- Testing logic regardless of authentication status
- Testing Modelβs basic CRUD operations
Internal Structure
getMockContext()
Mock Context is created as follows:session: Initialized asnull(unauthenticated state)user: Default isnull(unauthenticated state)naiteStore: Independent log storage per testlocale: Initialized as empty string
AsyncLocalStorage Isolation
Sonamu uses Node.jsAsyncLocalStorage to isolate Context:
- Context doesnβt mix between tests
- Safe for parallel test execution
- Each test has independent Naite log storage
How test() Wrapper Works
Sonamuβstest() function wraps Vitestβs test() to automatically provide Mock Context:
- Execute Vitestβs
test() - Create and activate Mock Context with
runWithMockContext() - Execute test function
- Collect Naite logs regardless of success/failure
- Automatic Context cleanup
testAs() Structure
testAs() receives additional user info to extend Context:
Cautions
Next Steps
Database Mocking
Isolating DB tests with transactions
API Mocking
Mocking external API calls
Naite Logging
Recording and tracking test logs
Bootstrap
Test environment initialization