Skip to main content
Learn how to write independent tests by mocking external dependencies like APIs, file systems, and timers.

What is API Mocking?

In testing, Mocking refers to providing fake behavior for external dependencies (APIs, file systems, time, etc.) without actually executing them. This enables:
  • Tests run regardless of external service outages
  • Fast tests without network calls
  • Stable tests with predictable results
  • Avoiding costly operations (payments, SMS, etc.)

Types of Mocking

Sonamu supports three types of mocking:

Vitest Mock

Vitest’s built-in mocking features

Naite Mock

Dynamic mocking with Naite

Manual Mock

Manually implemented mock objects

Using Vitest Mock

Module Mocking

Replace external module behavior with fakes:

Function Spy

Track actual function calls:

Timer Mocking

Control time-related functions:
bootstrap() and timers: Sonamu’s bootstrap() function automatically calls vi.useRealTimers() in afterEach to restore timers. No need to call it separately.

Date Mocking

Fix the current time:

Using Naite Mock

Use Naite’s special key patterns to create mocks dynamically.

File System Mocking

Creating Virtual Files

Register virtual files with the mock:fs/promises:virtualFileSystem key:

Practical Example: File Upload Test

How Naite Mock Works

Naite detects special key patterns (mock:*) to intercept corresponding behavior:

Implementing Manual Mock

Implement Mock classes directly for complex external services.

Creating Mock Class

Using Mock

Practical Examples

External API Call Mocking

SMS Sending Mocking

File Upload Mocking

Environment Variable Mocking

Mocking Strategy

Layer-based Mocking

Mocking by test level:
  1. Unit test: Mock all dependencies
  2. Integration test: Mock only external dependencies
  3. E2E test: Minimize mocking

Mock Data Management

Manage test mock data in separate files:
Usage:

Cautions

Cautions when mocking:
  1. Avoid excessive mocking: Too many mocks can diverge from actual behavior. Only mock what’s necessary.
  2. Clean up mocks: Not cleaning mocks in afterEach can affect other tests.
  3. Match mock and real behavior: If mock behavior differs from the real service, tests may pass but fail in production.
  4. Type safety: Specify types for mocks to prevent runtime errors.
  5. Naite Mock scope: mock:* keys work globally, so always delete them at test end.

Next Steps

runWithMockContext

Testing with Mock Context

Database Mocking

Isolating DB tests with transactions

Naite Logging

Recording and tracking test logs

Bootstrap

Test environment initialization