363 words
2 minutes
Using Mock Services in Front-End Projects

In decoupled front-end/back-end development, a mock service is a common technique for simulating backend APIs, letting front-end developers build and test independently.

What Is a Mock Service?#

A mock service is a stand-in for backend APIs. It returns simulated responses so that front-end development and testing can move forward without waiting for the real backend.

Why You Want One#

It improves throughput: front-end developers usually have to wait for the backend to finish an API before they can build against it. With a mock service, you develop and test against simulated data from day one.

Using a Mock Service in Your Project#

Most of the time you’re working in a framework like ice.js, umijs, or next.js — all of which ship with mock support built in.

But some projects don’t use a framework at all — a plain front-end project, say. In that case you have to stand up a mock service yourself, and Apifox is a good tool for the job.

Using Apifox as the Mock Service#

  1. Install Apifox.

  2. Typically the backend team provides the API docs and runs a local mock server; grab the mock base URL (for example: http://127.0.0.1:4523/m1/4945763-4603443-default/**/*).

  3. Point your front-end project’s API requests at the mock server.

    3.1 Projects usually keep an environment variable to separate development from production. Add this to env.development:

    Terminal window
    # apifox mock base url
    REACT_APP_APIFOX_BASE_API=http://127.0.0.1:4523/m1/4945763-4603443-default

    3.2 In development, route requests to the mock server by adding this to the request interceptor:

    service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
    const { isApifoxMock = false } = config.customConfig || {};
    if (isApifoxMock) {
    config.baseURL = process.env.REACT_APP_APIFOX_BASE_API;
    }
    return config;
    },
    error => {
    return Promise.reject(error);
    },

);

3.3 Configure the custom flag on the API call (`isApifxiMock === true`)
![Example configuration](./1.png)
If you're using `typescript`, add the following to `types.d.ts` under `src`:
```ts
declare module 'axios' {
export interface AxiosRequestConfig {
customConfig?: {
isApifoxMock?: boolean; // whether to route through the apifox mock
}
}
}
  1. Start the project, hit an endpoint, and check the mock data. Mock data in action

  2. Once the backend ships the real API, flip the custom flag to isApifxiMock === false and you’re talking to real data.

Wrapping Up#

Mock services play a big role in front-end development: they let you decouple front-end and back-end work early, which speeds up both development and testing.

Using Mock Services in Front-End Projects
https://www.mihouo.com/en/posts/front/using-mock-services-in-front-end-projects/
Author
Jia
Published at
2024-09-24
License
CC BY-NC-SA 4.0