How we use mocking in our front-end development at OY! Indonesia

Ashal Farhan
OY! Indonesia
Published in
4 min readOct 3, 2023

In the ever-evolving landscape of web development, the relationship between backend and frontend technologies has undergone a significant transformation. Traditionally, these two components were tightly interwoven, often leading to code entanglement, inefficiencies, and difficulties in scalability. As we embark on this journey, we will leverage the power of TypeScript and Axios, two robust tools that facilitate seamless communication between these distinct layers of web applications.

Problem Statement

When developing a feature, we know that the specification will be prepared first, and if it requires design, then the design team needs to create the design. After specification and design are done, the Backend Developer will start developing the API. Then, the Frontend Developer could start slicing and developing the interface if it’s done. If you notice, the Frontend Developer has a dependency for the API by the Backend. Which will result in a longer development time. The visualization will look something like this:

We can reduce the development time by decoupling the front-end and back-end development processes.

What is Decoupling

Decoupling is a separation of linked systems so that they may operate independently.

In this case, we could just let frontend engineers focus on crafting seamless user interfaces while backend engineers create the API. This will result in the following visualization:

You may be wondering:

What if the frontend is done with slicing the interface, but they need some APIs for rendering some data, and integrating the interaction?

API Mocking

Instead of sending requests to an actual API Server, we could just create a Mock API Server that responds to static data.

There are lots of API Mock libraries out there, one of them is connect-api-mocker. We use this because it’s basically just a simple Express Node.js Server that responds to some mock data. The benefits are:

  • Simple to use, because we just need to create a JSON file.
  • Powerful, since we could also have some logic inside of our handler.
  • No internet connection is needed, it’s just a local Node.js server.
  • Fewer changes when the real endpoint is ready.
  • Not bloating your codebase, the JSON mock files are stored separately in a dedicated package (if you’re using a mono repo).

You can find other alternatives here.

How it works

The concept here is that you need to use service names as the directory name and HTTP method as the filename. Middleware will match the URL to the directory structure and respond with the corresponding HTTP method file.

For example:

If you want to be more dynamic in the response, you could also create a handler in a JavaScript file. Let’s say that you want to add a validation in your handler, instead of POST.json, you can create a POST.js file that looks like the following:

module.exports = (request, response) => {
const { name } = req.body;
if (!name) {
response.status(400).json({
message: 'Product name must not be empty!',
});
return;
}
response.status(201).json({
message: 'Success creating a new product!',
});
};

Implementation

Since we are using axios, then you probably know that we could intercept every request or response of the axios by using interceptors. We can utilize this feature to dynamically change the base URL to the local Mock API server that we created if we want to mock the request:

const getProducts = () => {
return axios.request({
url: '/products',
method: 'GET',
mock: true,
});
};

Then inside the interceptor, we will determine if the request should be forwarded to our Mock API server or not by the mock config property:

const MOCK_BASE_URL = 'http://localhost:8080/api';

axios.interceptors.request.use(config => {
if (process.env.NODE_ENV !== 'production' && config.mock) {
config.baseURL = MOCK_BASE_URL;
}
});

TypeScript Issue

If you’re using TypeScript, then you will notice that you got an error when calling axios.request and passing mock property that says:

As the error says, we should tell TypeScript that themock property exists in AxiosRequestConfig interface. To solve this, create a new declaration file called axios.d.ts inside of the src/@typesdirectory:

import 'axios';

declare module 'axios' {
export interface AxiosRequestConfig {
mock?: boolean;
}
}

This is called Module Augmentation, which will tell TypeScript to merge the interface from this file with the declaration of the module itself.

Conclusion

When the real endpoint is deployed to the development/staging server, what you need to do is to remove the mock property from your axios client.

To generate the mock data, you can use Mockaroo. Not only for JSON data but also XML, CSV and SQL.

One of the challenges of this mocking API method is that the backend engineers must keep updating the API Contract whenever there’s a change so that frontend engineers can update the mock data/endpoints.

I hope this is useful to you, let me know if you have any problems or feedback about this article. Thank you!

--

--

Ashal Farhan
OY! Indonesia

A passionate web developer, focusing in the frontend development.