Mocking API Calls in React with Jest and MSW

⚛️ Top 150 React Interview Questions – 121/150 📌 Topic: Mocking API Calls ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Mocking API calls means creating a fake server response during testing instead of calling a real backend. Instead of waiting for a live API, you simulate what the server would return. 👉 Your test behaves as if the API responded — but no real network request is made. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY use it? ⚡ Speed Mocked tests run instantly. No network delay. 🔒 Stability Tests won’t fail because the backend is down. 🎯 Full Control You can simulate: 200 Success 404 Not Found 500 Server Error Empty response [] Without changing real backend code. 💰 Cost Efficient No need to hit production databases during CI/CD runs. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW to do it? Industry standard tools: Jest MSW (Mock Service Worker) ✅ Basic Jest Mock Example // 1. Fake API Response const mockResponse = { id: 1, name: "John Doe" }; // 2. Mock fetch test('renders user name', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(mockResponse), }) ); render(<UserComponent />); expect(await screen.findByText('John Doe')).toBeInTheDocument(); }); 👉 The component thinks it received real data. But the server was never contacted. 🔥 Pro Tip (Production-Ready Approach) Use MSW for realistic API interception instead of manually mocking fetch. It intercepts requests at the network level — cleaner and more scalable. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE to use it? 🧪 Integration Tests Components that fetch data inside useEffect. 🚀 CI/CD Pipelines Ensures automated tests run without real backend dependency. ⚠️ Edge Cases Test: Empty state UI Error UI Loading UI Without breaking real APIs. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY (Easy to Remember) Think of a Movie Set 🎬 If a scene needs a “Diamond,” the director doesn’t use a real one. They use a Glass Prop (Mock). It looks real on camera (the test), costs nothing, and avoids risking the real expensive diamond (Production Database). Mocks protect your real system while keeping your tests fast and reliable. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #Testing #Mocking #Jest #MSW #FrontendDevelopment #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories