Tillitsdone
down Scroll to discover

Mocking APIs & State in React Testing Library

Learn effective strategies for mocking API calls and managing state in React Testing Library.

Master practical techniques for writing reliable, maintainable component tests.
thumbnail

Mocking APIs and State Management in React Testing Library

An abstract modern architectural interior with flowing curves and geometric patterns dominated by sunshine yellow and amber tones shot from a low angle perspective looking upward high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Testing modern React applications can be challenging, especially when dealing with complex API calls and state management. Today, let’s dive into practical strategies for mocking APIs and testing state management using React Testing Library.

Understanding API Mocking

When testing components that make API calls, we don’t want to hit real endpoints. This would make our tests slow, unreliable, and dependent on external services. Instead, we use mocking to simulate API responses.

A geometric pattern of interlocking hexagons with smooth gradients featuring sapphire blue and seaweed green captured from a top-down aerial view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

The most common approach is to use Jest’s mocking capabilities along with MSW (Mock Service Worker). MSW lets us intercept network requests and provide mock responses, making our tests more predictable and maintainable.

Setting Up MSW

First, let’s set up MSW in our testing environment. We’ll create handlers that intercept our API calls and return mock data:

import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/api/users', (req, res, ctx) => {
return res(
ctx.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
])
);
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Testing State Management

When it comes to state management, whether you’re using Redux, Context API, or other solutions, React Testing Library encourages testing from the user’s perspective.

A close-up of weathered stone texture with intricate natural patterns featuring stone blue and gray tones photographed from an extreme macro perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Here’s a practical example of testing a component that fetches data and updates state:

test('displays user data after fetching', async () => {
render(<UserList />);
// Wait for loading state
expect(screen.getByText('Loading...')).toBeInTheDocument();
// Wait for user data
const users = await screen.findAllByRole('listitem');
expect(users).toHaveLength(2);
expect(users[0]).toHaveTextContent('John');
});

Best Practices

  1. Always test loading states
  2. Handle error scenarios
  3. Test state transitions
  4. Verify user interactions
  5. Keep tests focused and isolated

Remember, the goal is to test behavior, not implementation. Focus on what users see and interact with, rather than internal state mechanics.

Advanced Scenarios

Sometimes you’ll need to test more complex scenarios, like error handling or race conditions. MSW makes this straightforward:

test('handles API errors gracefully', async () => {
server.use(
rest.get('/api/users', (req, res, ctx) => {
return res(ctx.status(500));
})
);
render(<UserList />);
const errorMessage = await screen.findByText(/error fetching users/i);
expect(errorMessage).toBeInTheDocument();
});

A dramatic rocky asteroid surface with crystalline formations featuring fluorescent green and maroon colors shot from a ground level perspective with strong directional lighting high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

By following these patterns and principles, you’ll create more reliable and maintainable tests that give you confidence in your application’s behavior. Remember, good tests should be easy to write, easy to read, and provide value through catching real issues.

icons/logo-tid.svg
Talk with CEO
Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.