API Fundamentals
/Intermediate
Mock APIs
Definition
A simulated version of an API that intercepts requests and returns predefined fake responses, used when the real backend API is unavailable or too slow to use for testing.
Explain Like I'm New
A movie set. The houses look real on the outside, but there is nothing inside. A Mock API looks exactly like the real API (it returns the exact same JSON structure), but it has no real database or logic behind it.
Real World Example
The Backend team is taking 3 weeks to build the API. The Frontend team cannot sit around doing nothing. They create a Mock API using JSON Server that returns fake user data, allowing them to build the entire UI immediately. When the real API is done, they just swap the URL.
Common Use Cases
- •Frontend development speed
- •Unit testing
- •Isolating failures
Interactive Example
/* Using Mock Service Worker (MSW) to mock an API in a React Test */ import { rest } from 'msw'; import { setupServer } from 'msw/node'; // 1. Define the fake API behavior const server = setupServer( rest.get('/api/user', (req, res, ctx) => { return res(ctx.json({ firstName: 'Fake John' })); }) ); // 2. Start the interceptor before tests run beforeAll(() => server.listen()); // 3. Test the Frontend UI. // The UI thinks it hit the real API, but MSW intercepted it! it('displays the user name', async () => { render(<UserProfile />); expect(await screen.findByText('Fake John')).toBeInTheDocument(); });
Interview Questions
basic
- What tool intercepts network requests in the browser to return Mock API data? (Hint: MSW)
intermediate
- Why would you use a Mock API during automated Frontend Unit testing (like Jest) instead of hitting the real backend API?