In this article, we shall learn how to mock axios HTTP calls using jest. Mocking is a technique in which an operation is simulated with similar results as one would get carrying out the operation. Making actual calls in a test is counterproductive and is error-prone in most cases.

1. Setup project

Run the following command to bootstrap a new React project:

npx create-react-app testing-hooks

The above operation installs all dependencies we shall need. For testing, we shall be using @react-testing-libary as the test suite and jest as the test runner

2. Add fetch data logic

Add axios library. We shall be using this library to perform HTTP requests. We shall be fetching a to-do item from (jsonplaceholder)[]


import axios from 'axios'

export const API_URL = ''

export const fetchTodo = async ()=> {
 try {
   const res = await axios.get(API_URL)
   return res
 } catch (err) {
   return err

3. Add the test case

We wrap tests inside a describe function, inside we create a mock todo object and mock the HTTP get call provided by axios.


import axios from 'axios'
import { API_URL, fetchTodo } from './fetchTodo'


describe('fetch Todos', () => {

  describe('test fetch todos successful', () => {
    it('Should return a todo item', async () => {
      const mockFakeTodoItem = {
        "userId": 1,
        "id": 1,
        "title": "delectus aut autem",
        "completed": false

      const result = await fetchTodo()

  describe('test fetch todos successful', () => {
    it('fetches todos from the api', async () => {
      const networkError = 'ERR_AGAIN'
      axios.get.mockRejectedValueOnce(new Error(networkError))
      const result = await fetchTodo()


The call to fetchTodo works the way it would work when the actual call is made. If using post, the same applies.

There are other alternatives and approaches to achieving the same. Jest docs provide API references for assertions, mocking, and other nice things it has to offer.


Mocking is a great way to make testing easier and less error-prone. This is just a scratch on the surface and other things can be mocked such as timers