API mocking performs a major position within the software program improvement course of. It permits builders to simulate the precise APIs and obtain life like responses generated with customized information. For instance, you need to use mock APIs when writing unit checks or conditions the place exterior dependencies are unavailable to make issues simpler.
On this article, I’ll focus on what API mocking is, why we’d like it, and what totally different API mocking methods we are able to use in JavaScript.
What’s API Mocking?
API mocking is a course of through which builders imitate the precise APIs with mock APIs. These mock APIs behave equally to the precise APIs and carry out the fundamental performance required to develop or check.
For instance, there could also be dependencies with exterior APIs which are unavailable within the developer surroundings. In such situations, you need to use mock APIs to proceed the event uninterrupted till the precise exterior APIs come dwell.
As well as, there are situations the place the builders have to implement and check the entrance finish first or when two totally different improvement groups develop the entrance finish and again finish individually. In such instances, it’s at all times higher to examine whether or not the entrance finish is correctly functioning even when the precise again finish is just not obtainable. We are able to use API mocking to check and ensure that the entrance finish capabilities correctly.
Why Use Mock APIs?
- They assist to mock information when writing unit checks with out calling the dwell API.
- The entire improvement quickens because the front-end and back-end builders can work parallelly.
- They assist perform offline improvement.
- They will pace up the event course of if the true APIs are gradual.
- The entrance finish can act as a standalone utility with out back-end dependencies within the improvement part.
JavaScript Libraries for API Mocking
There are a number of JavaScript libraries obtainable for API mocking. Deciding on an acceptable library is step one. Listed here are among the most used JavaScript API mocking libraries:
- JSON Server—A quick and environment friendly node module that enables making a REST JSON net service shortly.
- MirageJS—That is an API mocking library for constructing, testing, and sharing JavaScript purposes impartial of back-end providers.
- Nock—An HTTP server mocking library ideally suited for testing front-end elements by making HTTP requests.
- Axios-mock-adapter—A JavaScript library for sending HTTP requests to APIs.
- Faker—It is a well-known library for producing faux information for testing.
JavaScript API Mocking Strategies: Examples
Now that you’ve got a transparent understanding of what API mocking is and why we’d like it, let’s see how we are able to create mock APIs utilizing among the aforementioned libraries.
Mock APIs for JavaScript apps with JSON server
We are able to use JSON Server to create demo REST APIs in minutes. JSON Server is a node module that enables the mocking of a REST API service with minimal configuration. JSON Server is without doubt one of the hottest selections for API mocking due to its effectivity and ease.
JSON Server additionally helps fundamental validations like responding with 400 if a file of the identical ID already exists when creating a brand new file and 404 if the entity is just not there.
Step 1—Putting in JSON Server
Step one is to put in the JSON Server globally. Then, you need to use it for any venture when wanted.
npm set up -g json-server |
Step 2—Creating the mock information file
Then, create a JSON file with the required mock information.
{ "customers": [ {"id":"1","name": "Nishani", "usertype": "Admin"}, {"id":"2","name": "Nishani", "usertype": "Manager"}, {"id":"3","name": "Nishara", "usertype": "Admin"}, {"id":"4","name": "Nimal", "usertype": "Manager"}, {"id":"5","name": "Nilantha", "usertype": "Manager"} ] }
Step 3—Beginning the server
After that, begin the server with the next command.
json-server --watch customers.json --port 8000 |
Step 4—Utilizing within the utility
JSON Server helps all GET, POST, PUT, PATCH,and DELETE request strategies. The next code reveals easy methods to use the JSON Server for CRUD operations in a React utility.
import http from "../http-common"; import axios from "axios"; export default axios.create({ baseURL: "http://localhost:8000", headers: { "Content material-type": "utility/json" } }); export const getAllUsers = () => { return http.get("/customers"); }; export const getUser = (id) => { return http.get(/customers/${id} ); }; export const createUser = (information) => { return http.publish("/customers", information); }; export const updateUsers = (id, information) => { return http.put(/customers/${id} , information); }; export const removeUser = (id) => { return http.delete(/customers/${id} ); };
Nonetheless, there are a number of drawbacks to utilizing JSON Server. As an illustration, JSON Server is just not versatile and can’t configure totally different question parameters for non-CRUD endpoints. Additionally, you want to arrange the check information once more if all of it will get unintentionally deleted, because the JSON Server makes a everlasting impression on the information.
Utilizing MirageJS for API Mocking
MirageJS is a client-side mocking framework that mocks the API within the browser by using the Pretender library. It has many built-in instruments: serializer, route handlers, database, fashions, fixtures, and factories. They permit emulating dynamic habits between the entrance finish and again finish, relatively than mocking the identical response again and again by hitting an endpoint.
Step 1—Putting in MirageJS
MirageJS set up is kind of easy with the next command.
npm set up --save-dev miragejs |
Step 2—Edit the server.js file
import { createServer } from 'miragejs'; export perform makeServer() { let server = createServer(); return server; }
The createServer perform creates a brand new mock server occasion.
Step 3—Refactor index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './elements/App'; import { makeServer } from './server'; if (course of.env.NODE_ENV === 'improvement') { makeServer({ surroundings: 'improvement' }); } ReactDOM.render( <React.StrictMode><App /></React.StrictMode>, doc.getElementById('root') );
The if situation within the earlier code is for utilizing the MirageJS server solely within the improvement part.
Step 4—Utilizing “Mannequin” in MirageJS
Server.js
import { createServer, Mannequin } from 'miragejs'; export perform makeServer({ surroundings="check" } = {}) { let server = createServer({ surroundings, fashions: { books: Mannequin, }, seeds(server) { server.create('e book', { title: 'Harry Potter: Philosophers Stone', physique: 'The story of a younger wizard on his journey to defeat an evil wizard who killed his dad and mom', }); server.create('e book', { title: 'Lunar Chronicles: Cinder', physique: 'A narrative the place the outdated fairy tales are retold however with an sudden finish', }); server.create('be aware', { title: 'Starvation Video games', physique: 'The thrilling story of Katnis Everdeen in a kill or die sport of survival', }); } }); return server; }
Step 5—Creating routes
routes() { this.namespace="api/books"; this.get('/', (schema, request) => { return schema.books.all(); }); this.get('/:id', (schema, request) => { let id = request.params.id; return schema.books.discover(id); }); this.publish('/', (schema, request) => { let attrs = JSON.parse(request.requestBody); return schema.books.create(attrs); }); this.patch('/:id', (schema, request) => { let newAttrs = JSON.parse(request.requestBody); let id = request.params.id; let e book = schema.books.discover(id); return e book.replace(newAttrs); }); this.delete('/:id', (schema, request) => { let id = request.params.id; return schema.books.discover(id).destroy(); }); }
- GET /api/books—fetch all e book data.
- GET /api/notes/:id —fetch a single e book file.
- POST /api/books —create a brand new e book file.
- PATCH /api/books/:id —replace an current e book file.
- DELETE /api/books/:id —take away an current e book file.
Step 6—Create and configure the entrance finish
The final step is to create or configure the present entrance finish to get the information created beforehand utilizing the routes.
A pattern output of the earlier information follows.
Learn extra: Mocking Again-ends for React Apps with MirageJS.
Axios-mock-adapter for API Mocking
The Axios-mock-adapter is an NPM library that enables mocking API requests. It’s fairly useful in testing and fron-tend improvement as this library will allow us to ship HTTP requests to an API.
Step 1—Set up the library
npm set up --save-dev axios-mock-adapter |
Step 2—Create and cross an Axios occasion to Axios adapter
The next code creates an Axios occasion after which passes it to the Axios adapter.
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 course of.env.isAxioMock? axiosMockInstance : axiosLiveInstance;
Now, we are able to import this file and use it the place essential.
Step 3—Create the mock file
import { axiosMockAdapterInstance } from 'src/lib/axios'; mock .onGet('/api/social/profiles') .reply(() => { const profile: Person = { id: 'u001', title: 'Supervisor', title: 'John Mayor', e-mail: 'johne@instance.com' }; return [200, { User }];
You’ll be able to learn extra about Axios Mocking with React right here.
Methods for API Mocking in JavaScript Purposes
An utility’s request journey includes three main elements:
- Software
- Request consumer
- Server
The applying calls a request consumer to make a request. The request consumer sends the request utilizing HTTP to the server. After receiving the request, the server returns the required response. So, we are able to mock the request consumer or the server as we check the applying.
Mocking the Request Consumer
The mock request consumer replaces the precise request consumer with a appropriate consumer to imitate the responses. You’ll be able to implement this system extra just by utilizing a third-party library like Nock and MirageJS.
The logical part of mocking is within the client-side code, and you may management the requests or responses at very early phases. Nonetheless, an precise request is just not made to the server by the request consumer when utilizing this technique.
Mocking the Server
The opposite technique for API mocking is mocking the server itself. On this case, the precise server will get changed with a mock server that accepts requests. Then it returns responses from and to the request consumer. We are able to use a number of libraries to perform this server mocking technique, together with JSON Server and ExpressJS server.
This technique is kind of just like the precise utility habits in manufacturing. The request consumer works fully as solely the server is changed right here. However organising and sustaining a complete server may be fairly pricey and complex. Subsequently, we are able to simplify the operations in server mocking to a sure extent through the use of the libraries talked about beforehand.
Conclusion
This text mentioned why API mocking methods are essential and what sort of methods we are able to use for API mocking, together with a number of examples. After all, whichever technique or library you employ will depend on the necessities of the situation and the surroundings, but it’s important to verify a naked minimal of utility habits change is going on because of the mocking.
So, I hope you discovered this text useful.
Thanks for studying!
Syncfusion’s Important JS 2 is the one suite you’ll ever have to construct an app. It accommodates over 65 high-performance, light-weight, modular, and responsive UI elements in a single bundle. Obtain a free trial to judge the controls at this time.
You probably have any questions or feedback, you possibly can contact us by way of our assist boards, assist portal, or suggestions portal. We’re at all times joyful to help you!