Use export default instance instead of export {instance}

Answer from aaronjkrause on Stack Overflow
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter
GitHub - ctimmerm/axios-mock-adapter: Axios adapter that allows to easily mock requests
const axios = require("axios"); ... reply are (status, data, headers) mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios .get("/users", { params: { searchText: ...
Starred by 3.5K users
Forked by 255 users
Languages   JavaScript 96.2% | TypeScript 3.8% | JavaScript 96.2% | TypeScript 3.8%
🌐
npm
npmjs.com › package › axios-mock-adapter
axios-mock-adapter - npm
October 9, 2024 - const axios = require("axios"); ... reply are (status, data, headers) mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios .get("/users", { params: { searchText: ...
      » npm install axios-mock-adapter
    
Published   Oct 09, 2024
Version   2.1.0
Author   Colin Timmermans
Discussions

Use axios and axios-mock-adapter
I'm trying to use axios and axios-mock-adapter in one place to aggregate more mocks and then export the axios instance to use it wherever I want: mock.js import axios from 'axios'; import MockAda... More on stackoverflow.com
🌐 stackoverflow.com
Newest 'axios-mock-adapter' Questions - Stack Overflow
I'm trying to use "axios-mock-adapter" lib to mock my API requests. Following the documentation, I need to create an instance of MockAdapter and use it in test cases. But actually, it ... ... I want to mock the Axios API in react-native and use axios-mock-adapter to mock the API. More on stackoverflow.com
🌐 stackoverflow.com
Recently Active 'axios-mock-adapter' Questions - Stack Overflow
I am using https://github.com/ctimmerm/axios-mock-adapter I would like to know how can I verify that an endpoint was actually called by the system under test. In this example: var axios = require('... ... I'm trying to test my axios API functions in React. More on stackoverflow.com
🌐 stackoverflow.com
reactjs - axios-mock-adapter onGet mock data not effective - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - React Testing: Mocking Axios with axios-mock-adapter Unless you fancy the built-in fetch API, chances are that you are using or have used axios as your HTTP client. If so, when writing tests you may …
🌐
Tabnine
tabnine.com › home page › code › javascript › axios-mock-adapter
axios-mock-adapter JavaScript and Node.js code examples | Tabnine
origin: yTakkar/React-Instagram-Clone-2.0 · const mockAxiosRequest = (endpoint, data) => mockAxios.onPost(`/api/${endpoint}`).reply(200, data) origin: wopian/kitsu ·
🌐
O'Reilly
oreilly.com › library › view › learn-react-with › 9781789610253 › 5d3268c8-806e-4e27-85d0-52440b34ab42.xhtml
Mocking Axios with axios-mock-adapter - Learn React with TypeScript 3 [Book]
Mocking Axios with axios-mock-adapter We are going to move to the project we created in Chapter 9, Interacting with Restful APIs. We are going to add a test that verifies the posts... - Selection from Learn React with TypeScript 3 [Book]
🌐
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 - Additionally, once we write an Axios GET request into our getData function, failing to properly mock the Axios request in our test can result in a nasty network error that will crash your test. Now that we’ve written our test. Let’s write some code to make it pass. import React, { Component } from "react"; import "./App.css"; import axios from "axios";class App extends Component { constructor() { super(); this.state = { rate: "" } this.getData = this.getData.bind(this); }async getData() { console.log('get data'); const result = await axios.get( "https://api.coindesk.com/v1/bpi/currentprice.json" ); this.setState({ rate: result.data.bpi.USD.rate_float }); } render() { return ( <div className="App"> <button className="btn" onClick={this.getData}> GET DATA </button> </div> ); } }export default App;
Find elsewhere
🌐
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.
🌐
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]) }) }) }) })
🌐
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.
🌐
Sergiojunior
sergiojunior.com.br › en › mocking-your-requests-like-a-pro
Sérgio Júnior - Mocking your requests like a pro
import MockAdapter from 'axios-mock-adapter'; import userMock from './mock'; const useMock = (axios) => { const mock = new MockAdapter(axios); mock.onGet(/all-users/).reply(200, userMock); mock.onGet(/single-user/).reply(200, userMock.users[0]); ...
🌐
Tabnine
tabnine.com › home page › code › javascript › mockadapter
axios-mock-adapter.MockAdapter.onPost JavaScript and Node.js code examples | Tabnine
mock.onPost('/user/create').reply(config => { return new Promise(function(resolve) { setTimeout(function() { const data = JSON.parse(config.data); users.push({ id: users.length + 1, ...data }); resolve([200, { message: 'OK', result: true }]); }, 1000); }); }); origin: danielzk/react-redux-testing-example · axiosMock.onPost(urls.userList()).reply(201, user) const store = mockStore(StoreFactory.build()) store.dispatch(createUser(user.username, user.firstName, user.lastName)) origin: tombenevides/sample-repo-app ·
🌐
Stack Overflow
stackoverflow.com › questions › tagged › axios-mock-adapter
Recently Active 'axios-mock-adapter' Questions - Stack Overflow
I am using https://github.com/ctimmerm/axios-mock-adapter I would like to know how can I verify that an endpoint was actually called by the system under test. In this example: var axios = require('... ... I'm trying to test my axios API functions ...
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);
    });
});
🌐
GitLab
docs.gitlab.com › ee › development › fe_guide › axios.html
Axios | GitLab Docs
import axios from '~/lib/utils... /users // arguments for reply are (status, data, headers) mock.onGet('/users').reply(200, { users: [ { id: 1, name: 'John Smith' } ] }); }); afterEach(() => { mock.restore(); });...
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 - Call the function you are testing (fetchUsers() in our example). Confirm that the request was sent to the correct endpoint and that the correct result is returned. The third way to mock Axios in Jest is to use the axios-mock-adapter library.
🌐
GitHub
gist.github.com › ademidun › 23d8da9be3235c094c5646f30a58edea
An example of how to use the axios-mock-adapter · GitHub
An example of how to use the axios-mock-adapter · Raw · APIMock.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
CloudDefense.ai
clouddefense.ai › code › javascript › example › axios-mock-adapter
Top 10 Examples of axios-mock-adapter code in Javascript
Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'axios-mock-adapter' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.