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 themock: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:-
Unit test: Mock all dependencies
-
Integration test: Mock only external dependencies
-
E2E test: Minimize mocking
Mock Data Management
Manage test mock data in separate files:Cautions
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