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);
    });
});
Answer from mgarcia on Stack Overflow
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);
    });
});
🌐
npm
npmjs.com › package › axios-mock-adapter
axios-mock-adapter - npm
October 9, 2024 - Note that passThrough requests are not subject to delaying by delayResponse. If you set onNoMatch option to passthrough all requests would be forwarded over network by default · // Mock all requests to /foo with HTTP 200, but forward // any others requests to server const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" }); mock.onAny("/foo").reply(200);
      » npm install axios-mock-adapter
    
Published   Oct 09, 2024
Version   2.1.0
Author   Colin Timmermans
Discussions

`onPost()` not mocking and returning actual Axios response
I originally posted on StackOverflow, but I didn't get any answers, and I have discovered a new side of this problem too. So, I thought I might have more luck finding a solution here! I am trying to use axios-mock-adapter to mock the res... More on github.com
🌐 github.com
4
July 30, 2024
Newest 'axios-mock-adapter' Questions - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... 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... More on stackoverflow.com
🌐 stackoverflow.com
unit testing - Mock axios with axios-mock-adapter get undefined resp - Stack Overflow
Attention!!! It is important in your case to create a new MockAdapter(api) using the api. If you create a MockAdapter(axios) will not work, this is a very common error. More on stackoverflow.com
🌐 stackoverflow.com
July 19, 2018
reactjs - Cant make axios-mock-adpter work properly - Stack Overflow
I trying to implement the axios-mock-adpter just for mock (not unit test) while the backend do they work. Im using Nextjs V.13,axios and axios-mock-adpter 1-AxiosMock and Mock Initializer import ax... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › issues › 166
Unable to mock axios instances · Issue #166 · ctimmerm/axios-mock-adapter
August 17, 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 › 395
`onPost()` not mocking and returning actual Axios response · Issue #395 · ctimmerm/axios-mock-adapter
July 30, 2024 - it("obtains an access code and a refresh token from the authorization code", async () => { const mockAxiosAdapter = new MockAdapter(axios); const mockTokenResponse = { data: { access_token: "DEF", refresh_token: "ABC" } }; const authResult = { type: "success", params: { code: "123" } } const authRequest = { codeVerifier: "XYZ" } mockAxiosAdapter.onPost(AuthManager.discovery.tokenEndpoint).reply(200, mockTokenResponse); await AuthManager.getTokenRequest(authResult as AuthSessionResult, authRequest as AuthRequest); expect(AsyncStorage.setItem).toHaveBeenCalledWith("access_token", "DEF"); expect(AsyncStorage.setItem).toHaveBeenCalledWith("refresh_token", "ABC"); }) })
Author   FionaLMcLaren
🌐
Stack Overflow
stackoverflow.com › questions › tagged › axios-mock-adapter
Newest 'axios-mock-adapter' Questions - Stack Overflow
I did a post request in Postman with adding Api-key in header from Authorization options which works completely fine but when i tried to do the same thing in React.js it gives me Network error. I ... ... I am using axios-mock-adapter to test my components. The strange thing is that only a single test can be run successfully because the next one always breaks.
🌐
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.
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › issues
Issues · ctimmerm/axios-mock-adapter
ctimmerm / axios-mock-adapter Public · Notifications · You must be signed in to change notification settings · Fork 256 · Star 3.6k · Search Issues · is:issue state:open · is:issue state:open Search · LabelsMilestonesNew issue · Open · Closed · Status: Open.
Author   ctimmerm
Find elsewhere
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter
GitHub - ctimmerm/axios-mock-adapter: Axios adapter that allows to easily mock requests
Note that passThrough requests are not subject to delaying by delayResponse. If you set onNoMatch option to passthrough all requests would be forwarded over network by default · // Mock all requests to /foo with HTTP 200, but forward // any others requests to server const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" }); mock.onAny("/foo").reply(200);
Starred by 3.5K users
Forked by 255 users
Languages   JavaScript 96.2% | TypeScript 3.8% | JavaScript 96.2% | TypeScript 3.8%
🌐
Snyk
snyk.io › advisor › axios-mock-adapter › axios-mock-adapter code examples
Top 5 axios-mock-adapter Code Examples | Snyk
beforeEach(() => { loadFixtures(fixture); // Re-declare this here so that test_setup.js#beforeEach() doesn't // overwrite it. mockAxios = new MockAdapter(axios); $.ajax = () => { throw new Error('$.ajax should not be called through!'); }; // These jQuery+DOM tests are super flaky so increase the timeout to avoid // random failures. // It seems that running tests in parallel increases failure rate. jest.setTimeout(4000); setTestTimeoutOnce(4000); }); ArkEcosystem / desktop-wallet / __tests__ / unit / store / modules / peer.spec.js View on Github · import axios from 'axios' import AxiosMockAdap
Top answer
1 of 1
1

The way you are doing, you are creating a new axios instance everytime, you need to create one, apply the mock to it, and then use this same instance. Also you need to specify the routes or use mock.onAny for example:

https://codesandbox.io/s/old-microservice-4gxxl4?file=/lib/axios.js

mock.js

import MockAdapter from "axios-mock-adapter";

export default function applyMockAdapter(axiosInstance) {
    const mock = new MockAdapter(axiosInstance);

    mock.onPost('/api/payments').reply(200, {
        status: "api/payments OK! "
    })

    mock.onAny().reply(200, {
        status: "Any other call will get this ",
        moreData: [1, 3, 4, 5,]
    })
}

axios.js

import axios from "axios";
import applyMockAdapter from "./mock";

const axiosInstance = axios.create({
    baseURL: "http://localhost:3000",
});

const someConfigToUseMock = true;

if (someConfigToUseMock) {
    applyMockAdapter(axiosInstance);
}

export default axiosInstance;

page.js

"use client";
import axiosInstance from '@/lib/axios'; // different name to avoid wrong import

export default function Home() {
  async function sendPayment() {
    const response = await axiosInstance // different name to avoid wrong import
      .post("/api/payments")
      .then((response) => {
        return response;
      })
      .catch((error) => {
        return error;
      });
    return response;
  }

  return (
    <button onClick={() => {
      sendPayment().then(console.log);
    }} >Make Request</button>
  )
}

If you need to use a function you need the fuction to always return the same instance like this:

import axios from "axios";
import MockAdapter from "axios-mock-adapter";

const axiosInstance = axios.create({
    baseURL: "http://localhost:3000",
  });

export function createAxiosInstace() {
 return axiosInstance;
}

const mock = new MockAdapter(createAxiosInstace());
export default mock;
🌐
UNPKG
unpkg.com › browse › axios-mock-adapter@1.18.1 › README.md
axios-mock-adapter
# axios-mock-adapter [![Build ...ck-adapter/dist/axios-mock-adapter.js - https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.min.js axios-mock-adapter works on Node as well as in a browser, it works with axios v0.9.0 and above....
🌐
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(); }); Because a polling function requires a header object, we need to always include an object as the third argument: mock.onGet('/users').reply(200, { foo: 'bar' }, {});
🌐
Reddit
reddit.com › r/reactjs › react-testing-library - what do you guys use to mock http requests?
r/reactjs on Reddit: React-Testing-Library - What do you guys use to mock HTTP requests?
February 7, 2021 -

I tried:

axios-mock-adapter

Axios test fails when you use a proxy in your package.json.

    Error: connect ECONNREFUSED 127.0.0.1:80

Other then that, it works great. But I'm unable to use my CI because it outputs the error above too.

Nock

Works great, but I can't seem to mock requests with headers sent (such as authorization). I find it hard to find information on how to solve the issue.

I'm wondering if there are other libraries I should try out (or bonus points if there is a solution to the problems above :)!

🌐
CodeSandbox
codesandbox.io › examples › package › axios-mock-adapter
axios-mock-adapter examples - CodeSandbox
Use this online axios-mock-adapter playground to view and fork axios-mock-adapter example apps and templates on CodeSandbox.
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › issues › 398
Unable to mock "no response received" · Issue #398 · ctimmerm/axios-mock-adapter
October 4, 2024 - Is it possible to mock a lack of a response? I'd like to test Axios error handling when a request is made but the server does not respond. If I use .timeout(), the request object on the AxiosError is not present. https://axios-http.com/d...
Author   adamgcoulon
🌐
Sergiojunior
sergiojunior.com.br › en › mocking-your-requests-like-a-pro
Sérgio Júnior - Mocking your requests like a pro
This way we just need to change the variable mockRequests to mock our requests or not. A better alternative might be use the npm package axios-mock-adapter.
🌐
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-mock-adapter and create a new instance, passing the axios module as an argument.