Mocking API Calls and Dependencies in React JS
Mocking is an essential part of testing in React applications. By mocking API calls and dependencies, you can isolate your components and ensure that tests focus on the functionality you want to verify. This article explores how to mock API calls and dependencies in React using Jest and other tools.
Why Mock API Calls?
- Test components without relying on real external services.
- Control the responses to test edge cases and error handling.
- Speed up tests by avoiding network requests.
Mocking API Calls with Jest
Jest provides powerful utilities for mocking functions, modules, and APIs. Below is an example of mocking an API call:
Example 1: Mocking with Jest for API Calls
// fetchData.js
export async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return response.json();
}
// fetchData.test.js
import { fetchData } from './fetchData';
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ id: 1, title: 'Test Post' }),
})
);
test('fetches data successfully', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1, title: 'Test Post' });
expect(fetch).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/posts/1');
});
Example 2: Mocking API Calls in Components
The following example demonstrates mocking API calls in a React component:
// FetchData.js
import React, { useEffect, useState } from 'react';
function FetchData() {
const [data, setData] = useState(null);
useEffect(() => {
async function getData() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const result = await response.json();
setData(result);
}
getData();
}, []);
return (
{data ? {data.title}
: Loading...
}
);
}
export default FetchData;
// FetchData.test.js
import { render, screen, waitFor } from '@testing-library/react';
import FetchData from './FetchData';
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ title: 'Mocked Post' }),
})
);
test('renders mocked API data', async () => {
render( );
expect(screen.getByText('Loading...')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText('Mocked Post')).toBeInTheDocument());
});
Mocking Dependencies with Jest
Sometimes, you need to mock dependencies like utility functions or external modules. Here’s how you can do it:
Example 3: Mocking Utility Functions
// mathUtils.js
export function multiply(a, b) {
return a * b;
}
// multiply.test.js
import * as mathUtils from './mathUtils';
jest.spyOn(mathUtils, 'multiply').mockImplementation(() => 10);
test('mocks multiply function', () => {
expect(mathUtils.multiply(2, 5)).toBe(10);
expect(mathUtils.multiply).toHaveBeenCalledWith(2, 5);
});
Example 4: Mocking External Libraries
You can mock external libraries using Jest's jest.mock
:
// axios.js
import axios from 'axios';
export async function fetchPost() {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
return response.data;
}
// axios.test.js
import axios from 'axios';
import { fetchPost } from './axios';
jest.mock('axios');
test('mocks axios get method', async () => {
axios.get.mockResolvedValue({ data: { id: 1, title: 'Mocked Axios Post' } });
const data = await fetchPost();
expect(data).toEqual({ id: 1, title: 'Mocked Axios Post' });
expect(axios.get).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/posts/1');
});
Best Practices for Mocking
- Mock only what is necessary to isolate the functionality being tested.
- Use Jest’s mocking features like
jest.fn()
andjest.mock()
effectively. - Verify that mocked dependencies are called with the correct arguments.
- Reset mocks after each test to avoid test interference.
Mocking API calls and dependencies helps create reliable and focused tests in React applications. By using Jest’s powerful mocking capabilities, you can simulate various scenarios, ensuring that your components and functions behave as expected.