Without using any other libraries:

import * as axios from "axios";

// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");

// ...

test("good response", () => {
  axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
  // ...
});

test("bad response", () => {
  axios.get.mockImplementation(() => Promise.reject({ ... }));
  // ...
});

It is possible to specify the response code:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));

It is possible to change the mock based on the parameters:

axios.get.mockImplementation((url) => {
    if (url === 'www.example.com') {
        return Promise.resolve({ data: {...} });
    } else {
        //...
    }
});

Jest v23 introduced some syntactic sugar for mocking Promises:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));

It can be simplified to

axios.get.mockResolvedValue({ data: {...} });

There is also an equivalent for rejected promises: mockRejectedValue.

Further Reading:

  • Jest mocking documentation
  • A GitHub discussion that explains about the scope of the jest.mock("axios") line.
  • A related question which addresses applying the techniques above to Axios request interceptors.
  • Using jest functions like mockImplementation in TypeScript: Typescript and Jest: Avoiding type errors on mocked functions
Answer from A Jar of Clay on Stack Overflow
🌐
npm
npmjs.com › package › axios-mock-adapter
axios-mock-adapter - npm
October 9, 2024 - const axios = require("axios"); const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance const mock = new AxiosMockAdapter(axios); // Mock GET request to /users when param `searchText` is 'John' // arguments for reply are (status, data, headers) mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios .get("/users", { params: { searchText: "John" } }) .then(function (response) { console.log(response.data); });
      » npm install axios-mock-adapter
    
Published   Oct 09, 2024
Version   2.1.0
Author   Colin Timmermans
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter
GitHub - ctimmerm/axios-mock-adapter: Axios adapter that allows to easily mock requests
const axios = require("axios"); const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance const mock = new AxiosMockAdapter(axios); // Mock GET request to /users when param `searchText` is 'John' // arguments for reply are (status, data, headers) mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios .get("/users", { params: { searchText: "John" } }) .then(function (response) { console.log(response.data); });
Starred by 3.5K users
Forked by 255 users
Languages   JavaScript 96.2% | TypeScript 3.8% | JavaScript 96.2% | TypeScript 3.8%
Top answer
1 of 7
257

Without using any other libraries:

import * as axios from "axios";

// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");

// ...

test("good response", () => {
  axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
  // ...
});

test("bad response", () => {
  axios.get.mockImplementation(() => Promise.reject({ ... }));
  // ...
});

It is possible to specify the response code:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));

It is possible to change the mock based on the parameters:

axios.get.mockImplementation((url) => {
    if (url === 'www.example.com') {
        return Promise.resolve({ data: {...} });
    } else {
        //...
    }
});

Jest v23 introduced some syntactic sugar for mocking Promises:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));

It can be simplified to

axios.get.mockResolvedValue({ data: {...} });

There is also an equivalent for rejected promises: mockRejectedValue.

Further Reading:

  • Jest mocking documentation
  • A GitHub discussion that explains about the scope of the jest.mock("axios") line.
  • A related question which addresses applying the techniques above to Axios request interceptors.
  • Using jest functions like mockImplementation in TypeScript: Typescript and Jest: Avoiding type errors on mocked functions
2 of 7
108

I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

🌐
Vhudyma-blog
vhudyma-blog.eu › 3-ways-to-mock-axios-in-jest
3 Ways To Mock Axios In Jest | Become Front-End Expert
July 5, 2021 - Learn three ways to mock Axios in Jest and test API requests - jest.mock() function, jest-mock-axios, and axios-mock-adapter libraries.
🌐
Snyk
snyk.io › advisor › axios-mock-adapter › axios-mock-adapter code examples
Top 5 axios-mock-adapter Code Examples | Snyk
beforeEach(() => { axiosMock = new MockAdapter(axios); }); vuesion / vuesion / src / app / shared / modules / auth / actions.spec.ts View on Github · beforeEach(() => { testContext = { dispatch: jest.fn() as Dispatch, commit: jest.fn() as Commit, state: AuthDefaultState(), } as ActionContext; mockAxios = new MockAdapter(HttpService); });
🌐
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 - If so, when writing tests you may need to mock API requests. 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.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › axios-mock-adapter
Newest 'axios-mock-adapter' Questions - Stack Overflow
I am trying to use axios-mock-adapter to mock the response I get when calling the Spotify API to request an access token. Here is the function that does just that...
🌐
AWS re:Post
repost.aws › questions › QUO7LllQQyQtWSs3jFLjwkag › mocking-axios-in-lambda-u-tests
mocking axios in lambda u tests | AWS re:Post
October 3, 2024 - import axios, { AxiosInstance } from "axios"; import { handler } from "./mylambda"; import MockAdapter from "axios-mock-adapter"; //https://stackoverflow.com/questions/45016033/how-do-i-test-axios-in-jest //https://stackoverflow.com/questions/60410731/how-to-mock-interceptors-when-using-jest-mockaxios/60413756#60413756 //https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js //jest.mock("axios"); //let mockAxios: any = jest.genMockFromModule("axios"); describe("test service", () => { let axiosInstance: AxiosInstance; beforeEach(() => { axiosInstance = { post: jest.fn(
Find elsewhere
🌐
Pashacraydon
pashacraydon.github.io › article › 2016 › 10 › 05 › testing-axios-with-axios-mock-adapter.html
Testing axios with axios-mock-adapter
import axios from 'axios' import MockAdapter from 'axios-mock-adapter' import expect from 'expect' import * as c from 'collections/utils/constants' import collectionsJSON from 'collections/tests/collections.json' const collections = collectionsJSON const collection = collections[0] describe('retrieveSingleCollection()', () => { it('should store the response from a successful GET request.', function () { const mock = new MockAdapter(axios) const collectionId = '123456789' mock.onGet(`${c.WEBSERVICE_ENDPOINT}/collections/${collectionId}/`).reply(200, collections[0]) return store.dispatch(retrieveSingleCollection(collectionId)) .then(() => { const { collection } = store.getState().collectionsState expect(collection).toEqual(collections[0]) }) }) }) })
🌐
GitLab
docs.gitlab.com › ee › development › fe_guide › axios.html
Axios | GitLab Docs
import axios from '~/lib/utils/axios_utils'; import MockAdapter from 'axios-mock-adapter'; let mock; beforeEach(() => { // This sets the mock adapter on the default instance mock = new MockAdapter(axios); // Mock any GET request to /users // arguments for reply are (status, data, headers) mock.onGet('/users').reply(200, { users: [ { id: 1, name: 'John Smith' } ] }); }); afterEach(() => { mock.restore(); });
🌐
Stack Overflow
stackoverflow.com › questions › 71813081 › mocking-all-axios-instances-with-axios-mock-adapter
node.js - mocking all axios instances with axios-mock-adapter - Stack Overflow
Unfortunatelly, attempting to mock the whole axios package in jest test (as below) when axios.create is called somewhere doesn't work: import axios from 'axios' import AxiosMockAdapter from 'axios-mock-adapter' const axiosMock = new AxiosMockAdapter(axios)
🌐
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 - 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>.
🌐
Daniel Gustaw
gustawdaniel.com › notes › how-to-mock-axios
Daniel Gustaw - How to mock Axios in Jest
import axios from "axios"; import MockAdapter from "axios-mock-adapter"; import {describe, beforeAll, afterEach,it, expect} from "@jest/globals"; import {getMyHexIp} from "./getMyHexIp"; describe("External axios call", () => { let mock: MockAdapter; beforeAll(() => { mock = new MockAdapter(axios); mock.onGet(`https://ipinfo.io/ip`).reply(200, '69.69.69.69'); }); afterEach(() => { mock.reset(); }); it("getMyHexIp", async () => { // when const result = await getMyHexIp() // then expect(mock.history.get[0].url).toEqual(`https://ipinfo.io/ip`); expect(result).toEqual('0x45454545'); }); });
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › issues › 166
Unable to mock axios instances · Issue #166 · ctimmerm/axios-mock-adapter
August 14, 2018 - // client.js import axios from 'axios'; const client = axios.create({ baseURL: process.env.REACT_APP_API_ROOT, responseType: 'json' }); export default client; // somecomponent.js import client from './client.js'; class SomeComponent extends React.Component { componentDidMount() { client.get('/foo/bar') .then(res => ...); } } When I try to test the component the call to the api is not intercepted by the mock and the real API is hit, causing errors in the test.
Author   ingro
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › issues › 377
onGet and other methods is not defined · Issue #377 · ctimmerm/axios-mock-adapter
August 2, 2023 - import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; const http = axios.create({ baseURL: `${process.ENV.SERVICE_API}`, headers: { 'Content-Type': 'application/json', }, }); describe('fetchAssetTypes', () => { beforeAll(() => { mock = new MockAdapter(http); }); afterAll(() => { mock.reset(); }); it('success', async () => { mock.onGet(/\/asset-types.*/).reply(200, mockTags); const result = await fetchAssetTypes({ codes: 'AP,AO' }); expect(result).toEqual(mockTags); }); });
Author   Shub1nk
🌐
Medium
medium.com › @zach.grusznski › how-to-use-axios-mock-adapter-to-test-network-requests-in-react-475e99cda5ea
How to use Axios Mock Adapter to test network requests in React | by Zach Grusznski | Medium
June 10, 2018 - Jest-cli version 20.0.4 seems to play best with enzyme at the moment. We’ll use enzyme-adapter-react-16 in a moment to do our set up, and axios-mock-adapter is how we will mock our API call in order to test it.
Top answer
1 of 1
3

There are a couple of problems in your code:

First, in the action creator you are using an axios instance to make the ajax call, but in the test you are not providing that instance to the axios-mock-adapter. You should provide your axios instance in your test when you create the instance of MockAdapter.

Second, the params property you are providing to the axios mock in the onGet method does not match the parameters that are sent in the get operation in your action creator. You should match the parameters in the call with their values. Thus, you should provide query and page params.

Last, you are returning the expectedActions in the mock request, but that does not seem right. Looking at your code, it seems that you want to return an empty array.

Having all that into account, your code would look like:

import MockAdapter from 'axios-mock-adapter';
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';

import axiosInstence from '../../apis/axiosInstence';
import { searchPhotos } from '../searchAction';

const mock = new MockAdapter(axiosInstence);

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const term = 'cars';
const store = mockStore({});

describe('actions', () => {
    beforeEach(() => {
        mock.reset();
        store.clearActions();
    });

    it('Should create an action to signIn with a fake user', async () => {
        const expectedActions = [{
            type: 'SEACH_REQUEST'
        }, {
            type: 'SEARCH_PHOTOS',
            payload: []
        }];

        mock.onGet('/search/photos', {
            params: {
                query: 'cars',
                page: 1
            }
        }).reply(200, []);

        const data = await store.dispatch(searchPhotos(term));
        const receivedActions = store.getActions();
        expect(receivedActions).toEqual(expectedActions);
    });
});