🌐
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
🌐
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%
🌐
Snyk
snyk.io › advisor › axios-mock-adapter › axios-mock-adapter code examples
Top 5 axios-mock-adapter Code Examples | Snyk
import axios from 'axios' import AxiosMockAdapter from 'axios-mock-adapter' import Vue from 'vue' import Vuex from 'vuex' import apiClient, { client } from '@/plugins/api-client' import store from '@/store' import peers, { goodPeer1, goodPeer2, goodPeer4, goodPeer5, badPeer1 } from '../../__fixtures__/store/peer' import { network1 } from '../../__fixtures__/store/network' import { profile1 } from '../../__fixtures__/store/profile' Vue.use(Vuex) Vue.use(apiClient) const axiosMock = new AxiosMockAdapter(axios) const nethash = '2a44f340d76ffc3df204c5f38cd355b7496c9065a1ade2ef92071436bd72e867' bef
🌐
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.
🌐
Tabnine
tabnine.com › home page › code › javascript › axios-mock-adapter
axios-mock-adapter JavaScript and Node.js code examples | Tabnine
before(() => { server = new MockAdapter(axios); server.onGet('/api/traces/searchableKeys').reply(200, stubSearchableKeys); server.onGet('/api/alerts/root-service/unhealthyCount').reply(200, 0); server.onGet('/api/services').reply(200, stubServices); server.onGet('/api/operations?serviceName=root-service').reply(200, stubOperations); server.onGet(/^\/api\/traces\?/g).reply(200, stubTraces); server.onGet(/^\/api\/traces\/timeline\?/g).reply(200, []); }); origin: wopian/kitsu ·
🌐
CloudDefense.ai
clouddefense.ai › code › javascript › example › axios-mock-adapter
Top 10 Examples of axios-mock-adapter code in Javascript
import axios from 'axios' import AxiosMockAdapter from 'axios-mock-adapter' import Vue from 'vue' import Vuex from 'vuex' import apiClient, { client } from '@/plugins/api-client' import store from '@/store' import peers, { goodPeer1, goodPeer2, goodPeer4, goodPeer5, badPeer1 } from '../../__fixtures__/store/peer' import { network1 } from '../../__fixtures__/store/network' import { profile1 } from '../../__fixtures__/store/profile' Vue.use(Vuex) Vue.use(apiClient) const axiosMock = new AxiosMockAdapter(axios) const nethash = '2a44f340d76ffc3df204c5f38cd355b7496c9065a1ade2ef92071436bd72e867' bef
🌐
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 …
🌐
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(); });...
🌐
Tabnine
tabnine.com › home page › code › javascript › mockadapter
axios-mock-adapter.MockAdapter.onPost JavaScript and Node.js code examples | Tabnine
January 21, 2022 - 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); }); }); ... axiosMock...
Find elsewhere
🌐
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...
🌐
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 - We will be using Jest and Enzyme for our testing stack as well as axios-mock-adapter to mock our requests. For this example, we will be using the CoinDesk API to retrieve the current bitcoin to US dollar exchange rate.
🌐
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]) }) }) }) })
🌐
GitHub
gist.github.com › 59ec4f9094219efa2e831f598d9d671a
How to use axios mock adapter · GitHub
How to use axios mock adapter · Raw · axiosMockAdapterUse.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.
🌐
GitHub
github.com › ctimmerm › axios-mock-adapter › releases
Releases · ctimmerm/axios-mock-adapter
October 9, 2024 - Change the parameters of the methods to align it to the one of axios. (#387) The last parameter must be a config object with {params, headers} instead of just the headers.
Author   ctimmerm
🌐
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 - Set the Mock Adapter on the default Axios instance: new MockAdapter(axios). Reset the mocked Axios object by calling: mock.reset() after each test in the afterEach hook, so that the state in the mock is cleared and each test starts fresh. Create a sample response and mock the call to the specific endpoint by using mock.onGet() function. Call the function you are testing (fetchUsers() in our example).
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

🌐
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. GitHub Gist: instantly share code, notes, and snippets.
🌐
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]
🌐
Npm
npm.io › package › axios-mock-adapter
Axios-mock-adapter NPM | npm.io
const axios = require("axios"); ... any GET request to /users // arguments for reply are (status, data, headers) mock.onGet("/users").reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios.get("/users").then(function (response) { console.log(response.data); ...