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:ip:127.0.0.1representing local environmentsession: Initialized as empty objectuser: Default isnull(unauthenticated state)passport: Mock functions, actual auth logic doesn’t executenaiteStore: Independent log storage per test
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: