Mocking APIs and Network Requests
๐งช Mocking APIs and Network Requests
๐น What is API Mocking?
Mocking an API means simulating the behavior of a real API so that you can test your application without making actual network requests. This helps in development and testing by:
Avoiding reliance on unstable or unavailable external services
Controlling response data (success, error, delay)
Speeding up tests and reducing costs
๐น Why Mock APIs?
Reason Benefit
API not ready Begin frontend/backend development early
Faster tests No delays from real network calls
More control Simulate edge cases, errors, timeouts
Isolate system components Focus on logic, not API behavior
๐น Common Use Cases
Frontend Testing (e.g., React, Vue)
Unit Tests for Services
Integration Testing
CI/CD pipelines
Offline development
๐น How to Mock APIs: Tools and Approaches
✅ 1. Frontend (JavaScript/TypeScript)
a. Using fetch-mock or msw (Mock Service Worker)
js
Copy
Edit
import { setupServer } from 'msw/node';
import { rest } from 'msw';
const server = setupServer(
rest.get('/api/user', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ name: 'John Doe' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
b. Axios Interceptors
js
Copy
Edit
axios.interceptors.request.use(config => {
if (config.url === '/api/user') {
return Promise.resolve({ data: { name: 'Mock User' } });
}
return config;
});
✅ 2. Python
a. Using unittest.mock or responses library
python
Copy
Edit
import requests
import responses
@responses.activate
def test_mock_api():
responses.add(
responses.GET, 'https://api.example.com/user',
json={'name': 'Alice'}, status=200
)
response = requests.get('https://api.example.com/user')
assert response.json()['name'] == 'Alice'
✅ 3. Node.js (Backend Testing)
a. Using nock
js
Copy
Edit
const nock = require('nock');
nock('https://api.example.com')
.get('/user')
.reply(200, { name: 'Jane Doe' });
✅ 4. Postman Mock Server
Create a Mock Server in Postman.
Define endpoints and sample responses.
Use the mock URL in your application instead of the real API.
๐น Best Practices
Practice Description
Use realistic data Mimic actual API responses
Test both success and error Include 404, 500, timeouts, etc.
Isolate test environment Don’t rely on real API calls in tests
Keep mocks versioned Sync with real API contracts/schema
๐น Summary
Mocking APIs and network requests helps you:
Develop independently of real APIs
Write fast and reliable tests
Simulate all kinds of scenarios (good and bad)
๐งฐ Tools vary based on your stack:
Frontend: MSW, fetch-mock, MirageJS
Backend: nock, responses, unittest.mock
General: Postman, WireMock
Would you like help setting up a mock server for your current project, or generating mock API documentation with OpenAPI?
Learn Playwright Training Course in Hyderabad
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment