📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

Mock API Setup in React: Methods, Use Cases, and Best Practices

Rohit Rajpal
Learn how to master mock API setup in React with key use cases and best practices to speed up development and improve testing accuracy.

When building React applications, developers often need to integrate APIs for data fetching or external service interactions. However, relying on real APIs during development can be impractical. This is where Mock APIs come in. A Mock API simulates real API responses, allowing developers to work without a backend service.

This article explores how to set up Mock APIs in React applications. We’ll cover tools, methods, and best practices to help you implement them effectively.

What is a Mock API?

A Mock API is a simulated version of a real API. Instead of calling an actual backend service, developers use a Mock API to simulate API responses, often mimicking the structure and behavior of a real API. This approach helps test and develop applications without the need for a live backend.

Mock APIs typically return predefined responses for specific requests, enabling developers to focus on building the frontend without waiting for the backend to be fully implemented. They can simulate data fetching, error handling, and various API behaviors, such as timeouts, making them essential for testing and development in isolation.

Why Mock APIs are Important

Here’s a deeper look at why Mock APIs are critical for a React development workflow:

  • Independent Frontend Development: Mock APIs allow frontend developers to work in parallel with backend teams, reducing bottlenecks. With mocked data, frontend work can continue even when the backend is in progress or unavailable.
  • Precise Control Over Data: Developers have full control over the data returned by API calls. This is especially useful when backend services are hard to predict. You can simulate various conditions, like error codes or slow responses, to test edge cases.
  • Realistic User Behavior Testing: Mock APIs let you introduce artificial delays, failures, or unreliable network conditions. This helps developers see how the app handles these issues, improving testing and UX.
  • Testing API Integration Without Dependencies: API endpoints can change unexpectedly and cause delays. With Mock APIs, development remains uninterrupted, and testing integration is possible without worrying about backend changes.
  • Cost and Resource Efficiency: Relying on third-party or paid APIs can rack up costs. Mock APIs eliminate this dependency, saving money and ensuring uninterrupted testing.

How Mock APIs Work in React

In React, Mock APIs allow developers to simulate real API responses, enabling development without the need for an actual backend. Instead of making live HTTP requests, the mock API intercepts those requests and returns predefined responses, helping you test how your application behaves under different scenarios, such as successful fetches, errors, or loading states.

Here’s how Mock APIs typically work in a React project:

  1. Set Up Mock API Tools: First, you need to select a tool or library, such as Requestly, to create your mock API. It helps you define mock endpoints and specify the responses they should provide.
  2. Define Mock Endpoints: Once the tool is in place, you define the mock API endpoints that your React app will use. For example, if you need user data, you might create an endpoint like /users to return mock data.
  3. Create Mock Responses: After setting up the endpoints, you specify what responses should be returned for each one. These could include JSON data, error messages, or simulated conditions such as timeouts to test how your app handles different scenarios.
  4. Integrate with Axios or Fetch: In your React components, you use standard HTTP methods like fetch or libraries like Axios to make API calls. Instead of hitting a real API, these requests are intercepted by your mock API and return the predefined responses.
  5. Simulate API Behavior: With the mock API set up, you can test your React application as though it’s interacting with a live backend. You can simulate various API conditions, such as successful requests, error codes, or timeouts, to see how the frontend handles them.
  6. Update Mocks as Needed: As your application evolves, you can modify the mock responses to match new data structures or changes in API behavior. This ensures your mock API stays in sync with the frontend, even as the backend changes.

Common Use Cases for Mock APIs in React

Mock APIs allow developers to continue building and testing applications even when backend services are unavailable or incomplete. Here are some common use cases:

  • Developing and Testing UI States: Mock APIs make it easy to build and test various UI states, such as loading indicators, empty lists, error messages, and success confirmations. Developers can simulate any API response to verify how components behave under different conditions without needing backend support.
  • Component-Level Testing: When writing unit or integration tests for components, mock APIs allow you to return controlled data and verify rendering logic, user interactions, and side effects. This ensures tests remain fast, stable, and independent of external services.
  • End-to-End Testing Without Network Dependencies: For E2E testing with tools like Cypress or Playwright, mocking APIs ensures the app behaves consistently regardless of network conditions or backend availability. Tests run faster and more reliably by bypassing real HTTP requests.
  • Simulating Error and Edge Cases: Mock APIs allow you to deliberately return 400 or 500 errors, invalid responses, or timeouts. This helps developers validate how the app handles real-world edge cases, ensuring error boundaries, fallbacks, and alerts work as expected.
  • Offline or Isolated Development: When working without internet access or when backend services are unavailable, mock APIs let developers continue coding and testing locally using simulated endpoints and data responses.
  • Prototyping and Stakeholder Demos: During early design reviews or product demos, mock APIs provide consistent and predictable data, making it easy to present a functioning UI without the need for real backend integration.
  • Performance and Latency Testing: Artificial delays can be introduced in mock responses to test how the UI handles slower network conditions. This is useful for fine-tuning loading states, fallback behavior, and user experience under stress.
  • Validating API Contracts: Mock APIs can be created based on agreed-upon API schemas (like OpenAPI or Swagger) before backend development is complete. This helps catch mismatches early and ensures frontend development aligns with backend contracts.

Advanced Mock API Setup in React: Strategies and Patterns

Once your basic mock API setup is in place, there are several advanced techniques that can significantly improve flexibility, realism, and maintainability. These patterns help simulate real-world conditions and align mock behavior more closely with production environments.

1. Simulating Network Latency and Failures

You can simulate network delays or errors using tools like Mock Service Worker (MSW) by adding delay or conditional error responses in your handlers. For example, to simulate a 2-second delay on a GET request:

rest.get('/api/data', (req, res, ctx) => {    
return res(      
ctx.delay(2000),      
ctx.json({ data: 'mocked data' })    
)  
})

This helps test loading spinners or retry logic.

2. Handling Authentication and Authorization

Mock auth flows by intercepting login requests and setting tokens in local storage or cookies. You can also protect routes conditionally:

rest.get('/api/profile', (req, res, ctx) => {    
const auth = req.headers.get('Authorization')    
if (auth !== 'Bearer valid-token') {      
return res(ctx.status(401), ctx.json({ message: 'Unauthorized' }))    
}    
return res(ctx.json({ user: { name: 'Jane Doe' } }))  
})

This way, your frontend can test protected content without a real backend.

3. Mocking REST vs. GraphQL APIs

For REST, mocking is endpoint-based like the examples above. For GraphQL, use tools like msw’s GraphQL utilities or Apollo’s mocking features to simulate schema-based responses:

import { graphql } from 'msw'  
export const handlers = [    
graphql.query('GetUser', (req, res, ctx) => {      
return res(ctx.data({ user: { id: '1', name: 'John' } }))    
})  
]

This lets you handle queries and mutations dynamically.

4. Automating Mock Data Creation

Libraries like Faker.js allow you to generate realistic random data inside your handlers:

import faker from 'faker'  
rest.get('/api/users', (req, res, ctx) => {    
const users = Array.from({ length: 5 }, () => ({     
 id: faker.datatype.uuid(),      
name: faker.name.findName(),      
email: faker.internet.email()    
}))    
return res(ctx.json(users))  
})

This saves time and improves test coverage for variable data.

5. Keeping Mocks Up-to-Date

To avoid drift between mocks and backend APIs, use API contract tools like Swagger or OpenAPI. You can generate mock servers automatically or validate your mock data against the spec using tools like Requestly.

6. Integrating Mocks with CI/CD

Include mock API startup scripts or MSW setup in your testing pipeline so tests run consistently. For example, in Jest, initialize MSW in setupTests.js and ensure it runs in your CI environment to avoid flaky tests caused by unavailable backends.

Testing and Mocking API Calls in React

Testing API calls in React is essential to ensure your application behaves correctly when interacting with backend services. It involves verifying that your components, hooks, or services properly handle successful responses, loading states, errors, and edge cases without relying on actual network calls during testing.

1. Mocking API Calls in Unit Tests

Unit tests focus on small, isolated pieces of code like components or functions. When those units make API calls, you need to mock the network requests to simulate different responses and avoid flaky tests caused by real API dependencies.

To do this, replace the real network call with a mock function that returns expected data or errors. This lets you control the response precisely. For example, if your component fetches user data, your mock might return a fixed user object or simulate a failure by returning an error.

You can also simulate delays or failures by adjusting the mock to return responses after a timeout or throwing errors. This helps test how your UI handles loading states or error messages.

In unit tests, the key steps are:

  • Replace actual API calls with mocked responses
  • Control the data returned for each test scenario
  • Verify component behavior for success, error, and loading states

2. End-to-End API Mocking Strategies

End-to-end (E2E) tests verify the complete user flow, including real interactions with the UI and API. However, relying on live backend APIs during these tests can lead to instability due to network issues, data changes, or downtime.

To create reliable and fast E2E tests, you can mock API responses at the network level. This means intercepting outgoing API requests during testing and returning predefined responses without hitting the real backend.

This approach allows you to:

  • Simulate all possible server responses (success, errors, edge cases)
  • Test app behavior under various network conditions
  • Run tests offline or in isolated environments without backend dependencies

During E2E testing, the mocked APIs should closely mimic the real backend’s behavior, returning data in the same format and with realistic timing to ensure test accuracy.

Why Use Requestly for Mock APIs in React?

Requestly is a browser-based tool that intercepts network requests made by your app and allows you to modify them in real-time. Instead of making actual calls to the backend, you can redirect requests, modify request headers, or even mock entire API responses from your browser.

This capability offers several unique advantages:

  • Instant Mocking Without Code Changes: You don’t need to write or maintain mock handlers inside your app. You simply configure Requestly to intercept and respond to specific API requests with custom data.
  • Flexible Testing of Edge Cases: By returning custom error codes or slow responses, you can simulate network failures, server errors, or latency without changing the app. This helps you verify how your React components behave under adverse conditions.
  • Testing Against Real Backend and Mocked Responses Side-by-Side: You can switch between real API calls and mocked responses easily, which is perfect for gradually transitioning from development to production or for quick troubleshooting.

Conclusion

Effectively testing and mocking API calls is crucial for building reliable React applications that handle real-world scenarios gracefully. By simulating various network conditions and server responses, developers can ensure their UI behaves correctly across success, failure, and edge cases without relying on unstable or incomplete backend services.

Requestly provides a powerful and flexible way to intercept and modify API requests directly in the browser, enabling instant mocking without code changes. It simplifies development, testing, and troubleshooting by allowing you to quickly switch between real and mocked responses, making it an invaluable tool for frontend teams working in dynamic environments.

Written by
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.

Related posts