Introduction

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)[https://jsonplaceholder.typicode.com/todos/1]

src/fetchTodo.ts

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
 }
}

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.

src/fetch.test.js

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

jest.mock('axios')

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
      }
      axios.get.mockResolvedValueOnce(mockFakeTodoItem)

      const result = await fetchTodo()
      expect(mockAxios.get).toHaveBeenCalledWith(API_URL)
      expect(mockAxios.get).toHaveBeenCalledTimes(1)
      expect(result).toEqual(mockFakeTodoItem)
    })
  })

  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()
      expect(result).toBe({})
    })
  })

})

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.

Summary

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