Skip to main content
Learn how to isolate tests and control authentication state using Mock Context.

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:
A simplified Mock Context is provided in tests:

Basic Usage

Regular Tests (Unauthenticated)

Sonamu’s test() function automatically runs runWithMockContext.

Direct Usage

You can also call runWithMockContext directly:

Testing as Authenticated User

Using testAs()

Use testAs() 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

Unauthenticated test
When 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:
Features:
  • session: Initialized as null (unauthenticated state)
  • user: Default is null (unauthenticated state)
  • naiteStore: Independent log storage per test
  • locale: Initialized as empty string

AsyncLocalStorage Isolation

Sonamu uses Node.js AsyncLocalStorage to isolate Context:
Benefits of isolation:
  • Context doesn’t mix between tests
  • Safe for parallel test execution
  • Each test has independent Naite log storage

How test() Wrapper Works

Sonamu’s test() function wraps Vitest’s test() to automatically provide Mock Context:
Process:
  1. Execute Vitest’s test()
  2. Create and activate Mock Context with runWithMockContext()
  3. Execute test function
  4. Collect Naite logs regardless of success/failure
  5. Automatic Context cleanup

testAs() Structure

testAs() receives additional user info to extend Context:

Cautions

Cautions when using Context:
  1. Cannot access Context outside test(): Sonamu.getContext() should only be called inside test functions. Returns undefined if called outside.
  2. Scope of Context modifications: Modifying Context affects the entire test. Automatically cleaned up when test ends.
  3. testAs() parameter order: User info is the first parameter.
  4. Type safety: User type for testAs() must extend AuthContext["user"].

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