Releases: onamfc/api-mocker
v1.0.4 - Initial Release
I am excited to announce the initial release of API Mocker, a lightweight TypeScript library designed to streamline frontend development by providing robust API mocking capabilities. This tool allows developers to build and test frontend applications independently of backend availability, simulate various API scenarios, and ensure a smoother development workflow.
Key Features
- Easy Integration: Seamlessly integrates with any HTTP client (e.g.,
fetch,axios). - TypeScript Support: Comes with full TypeScript definitions for enhanced type safety.
- Flexible Matching: Supports exact paths, dynamic parameters (
:id), query parameters, and request headers. - Advanced Matching: Custom matching logic can be defined for complex scenarios.
- Dynamic Responses: Create responses with custom logic based on request context.
- Stateful Mocks: Built-in state management for realistic CRUD operations and persistent data across requests.
- Network Error Simulation: Simulate various network conditions like timeouts, connection refused errors, and aborts.
- Priority System: Control mock precedence with configurable priority levels.
- Delay Simulation: Simulate network latency for realistic user experience testing.
- Request Logging: Optional logging to debug and monitor mock requests.
- Easy Switching: Simple enable/disable functionality to switch between mocked and real APIs.
- Zero Dependencies: No runtime dependencies, ensuring a lean and efficient library.
Requirements
- Node.js 18 or later for local development and testing.
- Browsers or runtimes that expose
fetch,Request, andResponseglobals. Polyfills may be required for older environments.
Quick Start Highlights
The library provides a straightforward setup process:
- Create Your Mock Setup File: Define your mock endpoints in a dedicated file (e.g.,
src/mocks/api-mocks.ts) usingcreateMockerand convenience methods likeget,post,put,patch,delete, ormockDynamicfor advanced logic. - Initialize Mocks in Your Application: Import and initialize your mocks early in your application's entry point (e.g.,
src/index.jsorsrc/main.tsxfor React,src/main.jsfor Vue), typically before your main application components are rendered. Environment variables (NODE_ENV,VITE_USE_MOCKS,REACT_APP_USE_MOCKS) can be used to conditionally enable mocks. - Use Your Regular HTTP Client: Your existing
fetchcalls will automatically be intercepted and respond with mocked data when enabled.
API Reference
The core of the library is the ApiMocker class, instantiated via createMocker(config?: MockConfig). Key methods include:
mock(endpoint)/mockDynamic(endpoint): Register static or dynamic endpoints.get,post,put,patch,delete: Convenience methods for common HTTP verbs.enable()/disable(): Toggle mock interception.clear()/remove(method, path): Manage registered mocks.setState(key, value)/getState()/clearState(): Manage in-memory state for dynamic handlers.updateConfig(partialConfig): Modify configuration at runtime.restore(): Restore the originalfetchimplementation.
Advanced Usage
The library supports advanced scenarios such as:
- Dynamic Responses with Custom Logic: Handlers can access
RequestContext(params, query, headers, body, state) to generate tailored responses. - Stateful CRUD Operations: Implement realistic create, read, update, and delete operations by managing state within your mocks.
- Advanced Request Matching: Match requests based on query parameters, request headers, or custom
matchfunctions. - Error Simulation: Configure
networkError(e.g.,'timeout','connection_refused','abort') or return HTTP error statuses.
Best Practices
I recommend organizing your mocks, using environment variables for control, employing realistic mock data, testing error scenarios, and leveraging TypeScript for type safety.
Contributing
I welcome issues and pull requests! Please visit the GitHub repository for more information.