Axios Mocking with ReactJS

Learn how to use the Axios Mocking Adapter to setup your in-memory Mock API for React

Axios is a JavaScript library that provides a simple interface to send HTTP requests to an API. Besides, it also provides the ability to Mock these endpoints to ease frontend development.

This article will discuss the importance of mocking and how to implement it with ReactJS and Axios.

Why Mock APIs with Axios?

Let’s begin with the question, “Why should we utilize Mock APIs?”. It’s not just because of a single reason. There are a few significant advantages, including;

  • The ability to Unit Test the frontend.
  • Developing frontend and backend with the least dependence.
  • Less iteration time (thus better developer experience) for frontend developers.

Since the benefits are clear, let’s look into how we can use Axios for mocking in practice.

1. Setting up Axios Mock Adapter

When it comes to mocking Axios, it all starts with the Mock Adapter. It’s a different NPM library that provides the additional capabilities to Mock the API requests.

You can install it using the command npm install –save-dev axios-mock-adapter.

Then, you need to create an Axios instance and pass it to the Axio adapter.

import axios, { AxiosRequestConfig } from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
const axiosMockInstance = axios.create();
export const axiosMockAdapterInstance= new AxiosMockAdapter(axiosMockInstance, { delayResponse: 0 });
export default axiosMockInstance;

You can see that I’ve exported both the Mock Adapter and Axios Mock instance in the above code. Each of them serves a different purpose.

  • Axios Mock Adapter Instance — This is used to define the Mock request handling code to define the Mock data.
  • Axios Mock Instance — This is used within React to invoke the API as a typical Axios instance.

2. Using the Mock Instance with React

Using the mock instance in React is straightforward. You don’t need to make any changes to the React code. The only thing is you have to import the correct instance in the component code.

But, if you use the above code snippet in a file name called libs/axios.ts you have to import the Axio instance from that file to invoke the API. So, as you can see, it creates a challenge, where you are locked to the Mock Instance.

To solve this problem, we can instantiate the Axio instance and return depending on environment variables. Moreover, it gives the option to switch between the two by simply changing a variable.

We can do that by modifying the above code snippet as follows.

import axios, { AxiosRequestConfig } from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
const axiosMockInstance = axios.create();
const axiosLiveInstance = axios.create();
export const axiosMockAdapterInstance= new AxiosMockAdapter(axiosMockInstance, { delayResponse: 0 });
export default process.env.isAxioMock? axiosMockInstance : axiosLiveInstance;

Now, we can import the above file and use it within React Components as usual.

3. Implementing the Mocks

Now, I’m getting into the most exciting part of the article to create our Mock files. The following example shows how we can create one e.g. _mock_/profile.ts

import { axiosMockAdapterInstance } from 'src/lib/axios';
mock
.onGet('/api/social/publications')
.reply(() => {
const profile: Profile = {
id: '5e8891ab188cd28',
avatar: '/static/mock-images/avatars/jane.png',
bio: 'Product Designer',
email: 'jane@test.com',
name: 'Jane'
};
return [200, { profile }];

If you closely check the imported file here, we have imported the Axios Mock Adapter instance we created in the previous file and added the mocking code.

We could have added the mocking code in the instance creation code itself. But, it makes it less flexible to create mock mocks as the file grows with time.

However, this approach creates another problem since the application doesn’t directly import these mock files. So either you have to import them one by one or use a different approach to import them all.

I’ve used the latter approach to import them all from my index.tsx file in the React app.

import './__mocks__';

Note: This isn’t the best approach in terms of optimization, but I wanted to avoid the hassle of importing one by one, just for now.

Available JavaScript Libraries for Mocking

I hope now you know how to set up the Axio mocking in detail. And, it’s important to note that Axio Mocking Adapter is just one way of mocking the API calls in React. There are other alternatives that you can try out. I’ve listed a few of them below.

Alternatively, you can use HTTP interceptors to mock API calls if you don’t want to utilize these libraries.

Summary

I hope you got a good understanding of using the Axios Mocking Adapter for API mocking with React. It will help you iterate faster in frontend development and save you time carrying out unit tests.

If you have any questions, do let me know in the comments below. Thanks for Reading !!

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


Axios Mocking with ReactJS was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by INDRAJITH

Learn how to use the Axios Mocking Adapter to setup your in-memory Mock API for React

Axios is a JavaScript library that provides a simple interface to send HTTP requests to an API. Besides, it also provides the ability to Mock these endpoints to ease frontend development.

This article will discuss the importance of mocking and how to implement it with ReactJS and Axios.

Why Mock APIs with Axios?

Let’s begin with the question, “Why should we utilize Mock APIs?”. It’s not just because of a single reason. There are a few significant advantages, including;

  • The ability to Unit Test the frontend.
  • Developing frontend and backend with the least dependence.
  • Less iteration time (thus better developer experience) for frontend developers.

Since the benefits are clear, let’s look into how we can use Axios for mocking in practice.

1. Setting up Axios Mock Adapter

When it comes to mocking Axios, it all starts with the Mock Adapter. It’s a different NPM library that provides the additional capabilities to Mock the API requests.

You can install it using the command npm install --save-dev axios-mock-adapter.

Then, you need to create an Axios instance and pass it to the Axio adapter.

import axios, { AxiosRequestConfig } from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
const axiosMockInstance = axios.create();
export const axiosMockAdapterInstance= new AxiosMockAdapter(axiosMockInstance, { delayResponse: 0 });
export default axiosMockInstance;

You can see that I’ve exported both the Mock Adapter and Axios Mock instance in the above code. Each of them serves a different purpose.

  • Axios Mock Adapter Instance — This is used to define the Mock request handling code to define the Mock data.
  • Axios Mock Instance — This is used within React to invoke the API as a typical Axios instance.

2. Using the Mock Instance with React

Using the mock instance in React is straightforward. You don’t need to make any changes to the React code. The only thing is you have to import the correct instance in the component code.

But, if you use the above code snippet in a file name called libs/axios.ts you have to import the Axio instance from that file to invoke the API. So, as you can see, it creates a challenge, where you are locked to the Mock Instance.

To solve this problem, we can instantiate the Axio instance and return depending on environment variables. Moreover, it gives the option to switch between the two by simply changing a variable.

We can do that by modifying the above code snippet as follows.

import axios, { AxiosRequestConfig } from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
const axiosMockInstance = axios.create();
const axiosLiveInstance = axios.create();
export const axiosMockAdapterInstance= new AxiosMockAdapter(axiosMockInstance, { delayResponse: 0 });
export default process.env.isAxioMock? axiosMockInstance : axiosLiveInstance;

Now, we can import the above file and use it within React Components as usual.

3. Implementing the Mocks

Now, I’m getting into the most exciting part of the article to create our Mock files. The following example shows how we can create one e.g. _mock_/profile.ts

import { axiosMockAdapterInstance } from 'src/lib/axios';
mock
.onGet('/api/social/publications')
.reply(() => {
const profile: Profile = {
id: '5e8891ab188cd28',
avatar: '/static/mock-images/avatars/jane.png',
bio: 'Product Designer',
email: 'jane@test.com',
name: 'Jane'
};
return [200, { profile }];

If you closely check the imported file here, we have imported the Axios Mock Adapter instance we created in the previous file and added the mocking code.

We could have added the mocking code in the instance creation code itself. But, it makes it less flexible to create mock mocks as the file grows with time.

However, this approach creates another problem since the application doesn’t directly import these mock files. So either you have to import them one by one or use a different approach to import them all.

I’ve used the latter approach to import them all from my index.tsx file in the React app.

import './__mocks__';

Note: This isn’t the best approach in terms of optimization, but I wanted to avoid the hassle of importing one by one, just for now.

Available JavaScript Libraries for Mocking

I hope now you know how to set up the Axio mocking in detail. And, it’s important to note that Axio Mocking Adapter is just one way of mocking the API calls in React. There are other alternatives that you can try out. I’ve listed a few of them below.

Alternatively, you can use HTTP interceptors to mock API calls if you don’t want to utilize these libraries.

Summary

I hope you got a good understanding of using the Axios Mocking Adapter for API mocking with React. It will help you iterate faster in frontend development and save you time carrying out unit tests.

If you have any questions, do let me know in the comments below. Thanks for Reading !!

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


Axios Mocking with ReactJS was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by INDRAJITH


Print Share Comment Cite Upload Translate Updates
APA

INDRAJITH | Sciencx (2021-11-04T01:29:50+00:00) Axios Mocking with ReactJS. Retrieved from https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/

MLA
" » Axios Mocking with ReactJS." INDRAJITH | Sciencx - Thursday November 4, 2021, https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/
HARVARD
INDRAJITH | Sciencx Thursday November 4, 2021 » Axios Mocking with ReactJS., viewed ,<https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/>
VANCOUVER
INDRAJITH | Sciencx - » Axios Mocking with ReactJS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/
CHICAGO
" » Axios Mocking with ReactJS." INDRAJITH | Sciencx - Accessed . https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/
IEEE
" » Axios Mocking with ReactJS." INDRAJITH | Sciencx [Online]. Available: https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/. [Accessed: ]
rf:citation
» Axios Mocking with ReactJS | INDRAJITH | Sciencx | https://www.scien.cx/2021/11/04/axios-mocking-with-reactjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.