Mock is both a shield and a weapon

Posted by MisterWebz on Mon, 24 Jan 2022 14:56:48 +0100

Front end mock

Now the development modes are generally front-end and back-end separated, so it is necessary to "accommodate" each other. For example, the background only defines the interface document in general, the interface has not yet come out, the front-end can not wait foolishly, but there is no coordination to develop, many details can not be taken into account. It's easy to get out of the interface when it's near the end of the work (you can't narrowly think that backstage is just meal) and to find out a lot of problems when interacting. That's too embarrassing. If it's delayed, the pot will easily cover up on the head of the front end and think the same way:

  • "Please" background speed up and ensure quality, which is a way to ask each time, please. (Often there are no eggs to worry about.)
  • My own mock interface, better "asynchronous" development with the background, quickly advance the progress of front-end work, expose problems as soon as possible, and strive for more time to solve for myself.

How to use mock

Install mockjs first

	yarn add -D mockjs

Then take a look at what your network request library is using:

axios:

	...
	import Mock from 'mockjs'
	...
	
	Mock.mock(apiUrl, mock)
	...

fetch: it has to be handled specially

Install mockjs-fetch first

	yarn add -D mockjs-fetch

Then?

	...
	import Mock from 'mockjs'
        import mockFetch from 'mockjs-fetch';
        mockFetch(Mock);
	...
	Mock.mock(apiUrl, mock)

This is the basic operation, but it is not enough.

How to use mock elegantly

I've seen a lot of projects, and often I've written a lot. Chestnut 🌰:

import Mock from 'mockjs'
import { builder, getBody } from '../util'

const login = options => {
  const body = getBody(options)
  return builder(
    {
      id: Mock.mock('@guid'),			//This @ is a placeholder for mockJs. You can check it on the official website. It doesn't matter. Our main code review is
      name: Mock.mock('@name'),
      username: 'admin',
      password: '',
      avatar:
        'https://gw.alipayobjects.com/zos/rmsportal/jZUIxmJycoymBprLOUbT.png',
      status: 1,
      telephone: '',
      lastLoginIp: '27.154.74.117',
      lastLoginTime: 1534837621348,
      creatorId: 'admin',
      createTime: 1497160610259,
      deleted: 0,
      roleId: 'admin',
      lang: 'zh-CN',
      token: '4291d7da9005377ec9aec4a71ea837f'
    },
    '',
    200
  )
}



Mock.mock(/\/auth\/login/, 'post', login)

First let's take a look. I don't know if my "aesthetic" is strange. I think this kind of code is a little awkward.

CodReview:

  1. First introduced mockjs in the header
  2. Then we introduced two tool functions, let's start with whatever
    import { builder, getBody } from '../util'
    
  3. Mock. Mock (/\/auth\/login/,'post', login) and then executed mock

Evaluation:

  1. em to and to, each time you write a mock module, you will refer to the mockjs library. If you repeat it, you can still bear it.
  2. em~~~~, why to introduce tool functions, why to know tool functions, or two! If you want to go beyond the basic mock, you can't say that, but it's just a mock, which is a bit... It's unbearable.
  3. what!!! The mock's interface address is "hard". Just think about the fear of hard coding. It's unbearable, unbearable!!!

Summary:

Repeated (even a few), focused (even a few), hard-coded (even one), and capable of refactoring can't be tolerated. We just want mock data, straight forward, naturally not good. Like literally, I think "mock" is an "api".

If an api is like this:

import BaseApi from './baseApi'

let config = {
    fetchLightAdd: "/light/fetchLightAdd",
    fetchLightUpdate: "/light/fetchLightUpdate",
    fetchLightDetail: "/light/fetchLightDetail",
    fetchTestDataList: "/light/fetchTestDataList",
}

export default new BaseApi({ config })

So what you want mock to look like is this:

import BaseMock from './baseMock'

let config = {
    fetchLightAdd: {
       ...
    },
    fetchLightUpdate: {
       ...
    },
    fetchLightDetail: (data) => {
        const { body = {} } = data;
        let params = JSON.parse(body);
        //Here the results are different for various simulation scenarios.
        if (params.id === "0") {
            return {
                code: "200",
                data: [{
                    lightName: "test_lightName_0",
                    comment: "test_comment_0",
                    lightItems: [{ lightItemId: 1, lightType: 0, baseSelect: 1, exclude: false }]
                }]
            }
        } else if (params.id === "1") {
            return {
                code: "200",
                data: [{
                    lightName: "test_lightName_1",
                    comment: "test_comment_1",
                    lightItems: [{ lightItemId: 1, lightType: 0, baseSelect: 0, exclude: 0 }, { lightItemId: 2, lightType: 1, baseSelect: 1, exclude: false }]
                }]
            }
        }

    },
    fetchTestDataList: {
        ...
    }
}

export default function mock(api) {
    new BaseMock({ config, apiConfig: api.getUrlConfig() })
}

Let's go to CodReview again:

  1. First, each file introduces mockjs: Solve 🆗, em~~~~is simply replaced by the introduction of BaseMock 😂, (I wanted to save this sentence, but I was afraid the code didn't understand it well, or I would have almost pulled the knife out 🐶)
  2. Multiple Focuses: Solving 🆗
  3. Hard Coding: Solution 🆗

Summary: is a simple data structure, provided to you, matching is over, think which interface of the mock, write this interface name, it is literal like that: I think "mock" a "api", other do not need your attention, it is so simple and natural.

Don't forget that mock s are only used in development mode.

Introduce dynamically based on the environment:

{
    /* Configure mock startup */
    const { NODE_ENV, MOCK } = process.env;
    if (NODE_ENV === "development") {
        if (MOCK != "none") {
            require('MOCK');
        }
    }
}

Remove the package when it is released. Is it not good to have a smaller package?

Options for configuring webpak s:

 //isEnvProduction is based on process. Env. NODE_ Judged by the ENVde value
 externals:isEnvProduction?{
            mockjs:mockjs
 }:{}

Pack it and let's see:

First Moderate Packing speed is still fast, only 21s, hey hey 😁

Then look at the report:

epilogue

Asking others to come is not as good as asking others to come. mock can really relieve a lot of pressure. The front end is not easy. The difficulty of ta is not that kind of redistribution to difficulty. It is really that kind of difficulty, that rare kind, that same difficulty as neuropathy.

Implementing Ideology 🌰

Topics: Javascript ECMAScript React