Mocking API Calls
0 620
🎠What is API Mocking?
Mocking API calls means simulating network requests in your tests without actually hitting a real backend server. It’s a common technique used in both frontend and backend testing to keep tests fast, predictable, and independent of external systems. Instead of waiting on actual HTTP responses, you “mock†them with custom data—allowing you to focus on how your app handles those responses.🧪 Why Mock API Calls in Tests?
- Faster tests: No real HTTP requests = lightning speed
- Better reliability: No network flakiness or backend downtime
- Control over edge cases: Easily test error responses, timeouts, etc.
- Test isolation: Each test runs in a controlled environment
🧰 Mocking in Unit & Component Tests (Jest + RTL)
Let’s say you have a function that fetches a user from an API: api.js
export async function fetchUser() {
const res = await fetch('/api/user');
return res.json();
}
api.test.js
import { fetchUser } from './api';
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: 'Aditya' })
})
);
test('fetches user data', async () => {
const data = await fetchUser();
expect(data.name).toBe('Aditya');
});
You’re mocking the global fetch function so no real API call is made. This keeps your unit tests fast and focused.
🧪 Mocking in React Component Tests
UserProfile.js
import React, { useEffect, useState } from 'react';
import { fetchUser } from './api';
function UserProfile() {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser().then(data => setUser(data));
}, []);
return user ? <p>Welcome, {user.name}!</p> : <p>Loading...</p>;
}
export default UserProfile;
UserProfile.test.js
import { render, screen } from '@testing-library/react';
import UserProfile from './UserProfile';
import * as api from './api';
jest.mock('./api');
test('renders fetched user name', async () => {
api.fetchUser.mockResolvedValue({ name: 'Aditya' });
render(<UserProfile />);
expect(await screen.findByText(/welcome, aditya/i)).toBeInTheDocument();
});
🌠Mocking APIs in End-to-End Tests (Cypress)
Cypress allows API mocking directly in your E2E test flow usingcy.intercept(). This helps you test UI behavior without depending on your real backend.
user.cy.js
describe('User Profile', () => {
it('displays mocked user info', () => {
cy.intercept('GET', '/api/user', {
statusCode: 200,
body: { name: 'Aditya' }
});
cy.visit('/profile');
cy.contains('Welcome, Aditya').should('exist');
});
});
Cypress intercepts the API call and responds with your mocked data—no real backend required. This gives you full control over test scenarios.
âš ï¸ Testing API Failures
Want to test how your app handles failures? Just mock a failed response:
// Jest
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.reject('Failed to load')
})
);
// Cypress
cy.intercept('GET', '/api/user', {
statusCode: 500,
body: { error: 'Server Error' }
});
This lets you validate error messages, retry logic, or fallback UIs with ease.
📦 Tools to Help With Mocking
- Jest – Built-in mocking for functions, modules, and fetch
- MSW (Mock Service Worker) – For network-level mocks in both tests and development
- Cypress Intercept – Easy API mocking in E2E browser tests
💡 Best Practices
- Mock only what you must: Don’t overuse mocks for everything
- Mock at the right level: Unit tests use Jest; E2E tests use Cypress or MSW
- Use consistent mock data: Reflect realistic use cases
- Test both success and failure paths
✅ Final Thoughts
Mocking API calls is a powerful skill that helps you write faster, more focused, and more reliable tests. Whether you’re writing a unit test in Jest or an E2E flow in Cypress, mocking gives you full control over external data—without relying on the backend. 🚀 The key is to keep mocks realistic, flexible, and purposeful. That way, your tests will remain stable while still delivering real-world confidence. 🛡ï¸If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments