Mock APIs: Different Techniques for React and Angular
Image by PIRO4D from PixabayIn web development, specialization improves productivity. In line with this, we can find developers who specialize in frontend or backend. However, splitting work and combining them
11.8k
By Kate Angelou
In web development, specialization improves productivity. In line with this, we can find developers who specialize in frontend or backend. However, splitting work and combining them to deliver functionality isn’t that easy when it comes to development. But the good news is, there are proven techniques that work in these circumstances.
To improve productivity, frontend developers can start their work by hardcoding values or mocking the backend API.
Mocking the backend is especially useful when delivering or sharing components as independent building blocks, using Bit (Github). As mentioned before, you don’t want to deliver front-end features without testing them first, but at the same time, you don’t want to be coupled to other developers or teams.
This article will show how you can begin frontend development (and even deliver it independently) by mocking the backend.
Here is a list of topics I’m going to direct your focus towards.
Why Mock APIs?
What should be mocked? — A list of common modules suitable for mocking
JavaScript Libraries Available for Mocking
Mock React/Angular apps with JSON server
Angular CRUD backendless application with interceptors
React CRUD backendless application with Axios mock adapter
React CRUD backendless application with JSON server and Mirage JS
All the examples explained in this article have the same logic with the same components and one HTTP service for calling CRUD endpoints. The only difference between each example application would be the way of mocking.You can find the links to full source code alongside the examples.
Let’s start our discussion with “Why should we use Mock API.” To begin with, have a look at the following benefits of Mock APIs.
Frontend developers and backend developers can work in parallel, hence fast development.
UI/UX developers can start only the required backend mock APIs
The frontend can act as a standalone application during development without any backend API dependencies.
Enable offline development
Easy to demo
The mock API can easily be replaced with the Real API once it’s ready.
Now that you have understood API Mocking's benefits let’s find out some common modules and operations suitable for mocking.
CRUD Operations — Create, Read, Update, and Delete operations in the application's main user flows.
Authentication and Authorization Flow
Pagination
Search/Sort
Error Handling — e.g., Timeouts, delays, validations, etc.
File Download
So how do you get started on mocking our APIs? You can start by choosing a suitable library. Here is a list of popular javascript libraries for mocking.
Apart from these libraries, you can also use Http Interceptors for mocking API calls.
JSON server is one of theeasiest and fastest ways of adding a mock REST API with a minimum configuration.
It offers basic validations like 404 if an entity is not found, 400 if the id already exists when trying to create a new entity. You can also check the network with browser dev tools to check the requests and responses.
The following are the steps to configure JSON Server.
HTTP interceptors offer more flexibility than the JSON server and eliminate the necessity of running a server separately. However, HTTP requests will NOT be visible in the network tab in the browser dev tools if you use HTTP interceptors.
You can configure an HTTP interceptor to intercept the requests and return responses. Give your attention to the following configurations.
You can use Axios mock adapter to intercept Http calls in React applications using Axios as an Http client. However, Axios mock adapter only supports Axios.
Here is how you’d configure the Axios Mock Adapter
Install axios-mock-adapter
npm install axios-mock-adapter --save-dev
The following code snippet shows how to intercept HTTP requests.
Mirage offers mocking facilities for a rest API with more elegant features than other libraries. You’d use Mirage on top of the JSON server to simulate some error scenarios.
Install Mirage JS
npm install --save-dev miragejs
mock-server.js
import {Response, Server} from "miragejs"// Create a new server instance - Intercepts the requests if (process.env.NODE_ENV === "development") { const server = new Server({ urlPrefix: "http://localhost:8000/", namespace: "", routes() { this.get("/countries/:id", (schema, request) => { let {id} = request.params; switch (id) { case "1": return new Response(404, {"Content-Type": "application/json"}, {error: 'Country not found'}); } }); }, });server.passthrough(); }
Mirage JS can act as a full-fledged mock server by injecting the data without using the JSON server. It also reloads mock data on browser refresh, unlike the JSON server. I have used both of them for simplicity and reducing some boilerplate code.
If you only need to mock simple CRUD endpoints with basic validations, you may use the JSON server. If you want a more flexible and customizable solution, choose HTTP interceptors or other libraries. You can combine the JSON server with other interceptor solutions like Mirage JS with the least configuration to increase the flexibility.
I hope these examples will help you choose a suitable mock API method for your frontend applications.
Thanks for reading, and if you have any questions, let me know in the comment box below. ?