The Home component directly depends on the patientServices module. In order to make the unit as small as possible, you should mock patientServices instead of axios.

The larger the unit, the more complex the test.

E.g.

Home.jsx:

import services from './services/patientServices';
import React, { useState, useEffect } from 'react';

export const Home = () => {
  const [patientSets, setPatientSets] = useState([]);

  const fetchPatientSets = async () => {
    try {
      const result = await services.patientSets();
      console.log('Data => ', result);
      setPatientSets(result.data);
    } catch (err) {}
  };

  useEffect(() => {
    fetchPatientSets();
  }, []);

  return (
    <div>
      <ul>
        {patientSets.map((p) => {
          return <li key={p.id}>{p.name}</li>;
        })}
      </ul>
    </div>
  );
};

apiClient.js

import axios from 'axios';

const apiClient = () => {
  const access_token = localStorage.getItem('access_token');
  const instance = axios.create({
    baseURL: window.config.apiUrl,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${access_token}`,
    },
    responseType: 'json',
  });
  return instance;
};

export default apiClient;

services/patientServices.js:

import apiClient from '../apiClient';

const patientSets = async () => {
  return await apiClient().get(`patient_sets`);
};

export default { patientSets };

Home.test.jsx:

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { Home } from './Home';
import services from './services/patientServices';

jest.mock('./services/patientServices');

describe('67122477', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const mResult = { data: [{ name: 'teresa teng', id: '1' }] };
    services.patientSets.mockResolvedValueOnce(mResult);
    render(<Home />);
    const matched = await screen.findByText(/teresa teng/);
    expect(matched).toBeInTheDocument();
  });
});

test result:

 PASS  examples/67122477/Home.test.jsx (11.771 s)
  67122477
    ✓ should pass (45 ms)

  console.log
    Data =>  { data: [ { name: 'teresa teng', id: '1' } ] }

      at examples/67122477/Home.jsx:10:15

---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------------|---------|----------|---------|---------|-------------------
All files            |   80.77 |      100 |    62.5 |   82.61 |                   
 67122477            |   85.71 |      100 |   83.33 |   84.21 |                   
  Home.jsx           |     100 |      100 |     100 |     100 |                   
  apiClient.js       |      50 |      100 |       0 |      50 | 4-13              
 67122477/services   |      60 |      100 |       0 |      75 |                   
  patientServices.js |      60 |      100 |       0 |      75 | 4                 
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.449 s
Answer from Lin Du on Stack Overflow
🌐
Bitstack
blog.bitsrc.io › axios-mocking-with-reactjs-85d83d51704f
Axios Mocking with React. Learn how to use the Axios Mocking… | by INDRAJITH EKANAYAKE | Bits and Pieces
March 4, 2025 - Axios Mocking with React Learn how to use the Axios Mocking Adapter to setup your in-memory Mock API for React Axios is a JavaScript library that provides a simple interface to send HTTP requests to …
Top answer
1 of 1
1

The Home component directly depends on the patientServices module. In order to make the unit as small as possible, you should mock patientServices instead of axios.

The larger the unit, the more complex the test.

E.g.

Home.jsx:

import services from './services/patientServices';
import React, { useState, useEffect } from 'react';

export const Home = () => {
  const [patientSets, setPatientSets] = useState([]);

  const fetchPatientSets = async () => {
    try {
      const result = await services.patientSets();
      console.log('Data => ', result);
      setPatientSets(result.data);
    } catch (err) {}
  };

  useEffect(() => {
    fetchPatientSets();
  }, []);

  return (
    <div>
      <ul>
        {patientSets.map((p) => {
          return <li key={p.id}>{p.name}</li>;
        })}
      </ul>
    </div>
  );
};

apiClient.js

import axios from 'axios';

const apiClient = () => {
  const access_token = localStorage.getItem('access_token');
  const instance = axios.create({
    baseURL: window.config.apiUrl,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${access_token}`,
    },
    responseType: 'json',
  });
  return instance;
};

export default apiClient;

services/patientServices.js:

import apiClient from '../apiClient';

const patientSets = async () => {
  return await apiClient().get(`patient_sets`);
};

export default { patientSets };

Home.test.jsx:

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { Home } from './Home';
import services from './services/patientServices';

jest.mock('./services/patientServices');

describe('67122477', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const mResult = { data: [{ name: 'teresa teng', id: '1' }] };
    services.patientSets.mockResolvedValueOnce(mResult);
    render(<Home />);
    const matched = await screen.findByText(/teresa teng/);
    expect(matched).toBeInTheDocument();
  });
});

test result:

 PASS  examples/67122477/Home.test.jsx (11.771 s)
  67122477
    ✓ should pass (45 ms)

  console.log
    Data =>  { data: [ { name: 'teresa teng', id: '1' } ] }

      at examples/67122477/Home.jsx:10:15

---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------------|---------|----------|---------|---------|-------------------
All files            |   80.77 |      100 |    62.5 |   82.61 |                   
 67122477            |   85.71 |      100 |   83.33 |   84.21 |                   
  Home.jsx           |     100 |      100 |     100 |     100 |                   
  apiClient.js       |      50 |      100 |       0 |      50 | 4-13              
 67122477/services   |      60 |      100 |       0 |      75 |                   
  patientServices.js |      60 |      100 |       0 |      75 | 4                 
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.449 s
🌐
C.S. Rhymes
csrhymes.com › 2022 › 03 › 09 › mocking-axios-with-jest-and-typescript.html
Mocking axios in Jest tests with Typescript | C.S. Rhymes
March 9, 2022 - Once I had got this example React app working, I tried to apply the same changes to another React project. This had a different set up and had a different Jest configuration. For some reason the above didn’t work with the other app. I got an error message, TypeError: Cannot read properties of undefined (reading 'then'). I don’t know the reasoning for this and unfortunately I can’t find the link to the forum that had the resolution for this, but I had to change jest.Mocked<typeof axios> to jest.MockedFunction<typeof axios>.
🌐
DEV Community
dev.to › nachothegre8t › mocking-axios-get-requests-a-practical-guide-for-reliable-react-testing-using-jest-3kik
Mocking Axios GET Requests: A Practical Guide for Reliable React Testing using Jest - DEV Community
January 23, 2024 - The objective of this comprehensive guide is to provide you with a clear understanding of how to efficiently mock external API response when utilizing Axios, ensuring a consistent and reliable testing environment. ... JavaScript Fluency: Understanding JavaScript is essential for working with React ...
🌐
npm
npmjs.com › package › axios-mock-adapter
axios-mock-adapter - npm
const normalAxios = axios.create(); const mockAxios = axios.create(); const mock = new AxiosMockAdapter(mockAxios); mock .onGet("/orders") .reply(() => Promise.all([ normalAxios.get("/api/v1/orders").then((resp) => resp.data), normalAxios.get("/api/v2/orders").then((resp) => resp.data), { id: "-1", content: "extra row 1" }, { id: "-2", content: "extra row 2" }, ]).then((sources) => [ 200, sources.reduce((agg, source) => agg.concat(source)), ]) ); The history property allows you to enumerate existing axios request objects.
      » npm install axios-mock-adapter
    
Published   Oct 09, 2024
Version   2.1.0
Author   Colin Timmermans
🌐
Apidog
apidog.com › blog › react-mock-api-axios
Mastering API Testing with React Mock API and Axios
July 24, 2024 - Discover how to master API testing in React with Axios and mock APIs. Learn the essentials of setting up Axios, creating mock APIs, and enhancing your testing workflow with Apidog.
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
import axios from 'axios'; import Users from './users'; jest.mock('axios'); test('should fetch users', () => { const users = [{name: 'Bob'}]; const resp = {data: users}; axios.get.mockResolvedValue(resp); // or you could use the following depending on your use case: // axios.get.mockImplementation(() => Promise.resolve(resp)) return Users.all().then(data => expect(data).toEqual(users)); });
🌐
Medium
simonkkaranja.medium.com › react-testing-mocking-axios-with-axios-mock-adapter-e24752a55923
React Testing: Mocking Axios with axios-mock-adapter | by Simon Karanja | Medium
December 14, 2020 - You could of course use mock functions provided by your test library in this case Jest, but I have found a nifty package called axios-mock-adapter to be excellent and natural when testing codes with axios implementation. Lets write a test for a simple component that fetches some random todos. A fully working implementation can be be found here. You can also see the code in action on this codesandbox. ... git clone https://github.com/karanja-simon/axios-mocking.git // Then switch to the clean branch (no tests yet).
Find elsewhere
🌐
Vhudyma-blog
vhudyma-blog.eu › 3-ways-to-mock-axios-in-jest
3 Ways To Mock Axios In Jest | Become Front-End Expert
Learn three ways to mock Axios in Jest and test API requests - jest.mock() function, jest-mock-axios, and axios-mock-adapter libraries.
Top answer
1 of 2
3

You must mock axios and look if axios methods are called with the right parameters for example.

apis.spec.js

import apis from './apis';

jest.mock('axios'); // This overwrites axios methods with jest Mock
import axios from 'axios';

describe('Test Apis', () => {
    describe('getResource', () => {
        describe('with success', () => {
            const url = 'http://test-url.com';
            const onComplete = jest.fn();
            const data = {};

            beforeEach(() => {
                axios.get.mockResolvedValue(data);
            });

            it('should call axios get with given url', () => {
                getResource(url, onComplete);
                expect(axios.get).toBeCalledWith(url);
            });

            it('should call onComplete callback with response', async () => { // do not forget 'async'
                await getResource(url, onComplete); // notice the 'await' because onComplete callback is called in '.then'
                expect(onComplete).toBeCalledWith(data);
            });
        });
    });
});

You could do the same with the error response and POST method. You could also test your LookingGlassAPIs by mocking your apis.js methods, or again by mocking axios, it depends of your "unit" definition inside your project.

2 of 2
0

As long as the functions you want to test don't return anything, you could test if they throw or no.

You would need to spy your axios methods, mocking a return value (in this case a Promise), something like:

import axios from 'axios';
    
beforeAll(() => {
  axios.get.mockImplementation(() => Promise.resolve('whatever-get'));
  axios.post.mockImplementation(() => Promise.resolve('whatever-post'));
});
    
afterAll(() => {
  jest.clearAllMocks();
});
    
test('get does not throw', () => {
  expect(getResource()).not.toThrow();
});
    
test('post does not throw', () => {
  expect(postResource()).not.toThrow();
});
🌐
Naftalimurgor
naftalimurgor.com › introduction-to-mocking-axios
Mocking Axios GET calls with Jest :: naftalimurgor.com - Example site for hugo-theme-tailwind
April 13, 2022 - For testing, we shall be using @react-testing-libary as the test suite and jest as the test runner · Add axios library. We shall be using this library to perform HTTP requests. We shall be fetching a to-do item from (jsonplaceholder)[https://jsonplaceholder.typicode.com/todos/1] ... import axios from 'axios' export const API_URL = 'https://jsonplaceholder.typicode.com/todos/1' export const fetchTodo = async ()=> { try { const res = await axios.get(API_URL) return res } catch (err) { return err } }
🌐
Medium
medium.com › simform-engineering › mocking-http-request-in-react-using-mock-service-worker-0f9c5400b035
Mocking HTTP Request in React using Mock Service Worker | by Vidhi Kapadia | Simform Engineering | Medium
December 28, 2023 - Nock is a Node.js library specifically ... behaviour and defining expected responses. axios-mock-adapter is a lightweight and easy-to-use mocking library specifically designed for Axios....
🌐
Stack Overflow
stackoverflow.com › questions › 63015489 › mock-axios-request-in-react
reactjs - Mock Axios request in React - Stack Overflow
import React from 'react'; import { render, cleanup, screen, waitForElement, } from '@testing-library/react'; import { Destination } from './Destination'; import axiosMock from 'axios'; afterEach(cleanup); describe('Destination', () => { it('Renders <Destination /> component', async () => { const route = { destinations: ['GVA'] }; const url = `${process.env.REACT_APP_API_BASE_URL}/destinations/GVA`; axiosMock.get.mockResolvedValueOnce({ result: { city: 'Geneva', iata: 'GVA' }, }); render(<Destination route={route} />); expect(screen.getByTestId('loading')).toHaveTextContent('Loading...'); const spanResolved = await waitForElement(() => screen.getByTestId('resolved') ); expect(spanResolved).toHaveTextContent('Geneva (GVA)'); expect(axiosMock.get).toHaveBeenCalledTimes(1); expect(axiosMock.get).toHaveBeenCalledWith(url); }); });
🌐
Medium
ooanishoo.medium.com › mock-axios-with-jest-and-react-testing-library-in-typescript-react-1c084d9ea880
Mock axios with Jest and React Testing Library in Typescript (React) | by Anish | Medium
April 12, 2021 - // src/api/index.spec.ts import axios, { AxiosResponse } from 'axios'; import { getTodos } from '.';//jest.mock(...) is used to automatically mock the axios module.jest.mock('axios');// Create an object of type of mocked Axios.
🌐
Stack Overflow
stackoverflow.com › questions › 63713628 › mock-axios-instance-and-interceptors-in-react-component-jest-test
reactjs - Mock Axios instance and interceptors in React component jest test - Stack Overflow
How do I go about mocking the api call to mock the data for my tests to pass?? ... test('<EmailTable/> ', async () => { const { debug, getByText } = render(<CommunicationEmail />); await waitFor(() => expect(getByText('Test Email Subject')).toBeTruthy()); } ... const instance = axios.create({ baseURL: `${apiUrl}/v1`, timeout: 12000, withCredentials: true, headers: headers, }); //intercept requests to validate hashed auth token instance.interceptors.request.use((request) => { const token = request.headers['X-Our-Access-Token']; if ( localStorage.getItem('user_token') == null || SHA256(token).to
🌐
Medium
medium.com › @conboys111 › master-mocking-api-calls-a-step-by-step-guide-for-react-testing-f5dd73524e16
Master Mocking API Calls: A Step-by-Step Guide for React Testing | by myHotTake | Medium
December 10, 2024 - Control the Action: Use mocks to simulate different scenarios (success, failure, etc.) without hitting the real API. Keep It Clean: Always clean up mocks after tests so they don’t interfere with other scenes. Libraries Help: Jest and @testing-library/react make mocking and testing React components a breeze.
🌐
npm
npmjs.com › package › jest-mock-axios
jest-mock-axios - npm
Axios mock for Jest. Latest version: 4.9.0, last published: 6 months ago. Start using jest-mock-axios in your project by running `npm i jest-mock-axios`. There are 21 other projects in the npm registry using jest-mock-axios.
      » npm install jest-mock-axios
    
Published   Sep 04, 2025
Version   4.9.0
Author   knee-cola
🌐
Leighhalliday
leighhalliday.com › mocking-axios-in-jest-testing-async-functions
Mocking Axios in Jest + Testing Async Functions | Leigh Halliday
Our version of "mock axios" will be an object with 1 property called get whose value is a function. ... Notice it isn't a regular arrow function though, it is a mock function. Jest mock functions, sometimes also known as "spy" functions, give ...
🌐
Robin Wieruch
robinwieruch.de › axios-jest
How to test Axios in Jest by Example
How to mock Axios in Jest by example for mocking get and post requests, for mocking network errors like a 404, and for testing Axios in React and Enzyme ...
🌐
Stack Overflow
stackoverflow.com › questions › 68562765 › how-to-mock-axios-in-react-with-using-axios-create-function
reactjs - How to mock axios in React with using axios.create function - Stack Overflow
import mockedAxios, {AxiosResponse} from "axios"; import streamsApi from '../apis/streams' import expectedStreams from "../mocks/expectedStreams"; jest.mock('axios') describe('fetchStreams action', () => { it('Store is updated correctly', async () => { const mockedResponse: AxiosResponse = { data: expectedStreams, status: 200, statusText: 'OK', headers: {}, config: {} } mockedAxios.get.mockImplementationOnce(() => { Promise.resolve(mockedResponse); }) const results = await streamsApi.get('/streams'); expect(results.data).toBe(mockedResponse.data); }); });