Mock is both a shield and a weapon

Time:2021-9-4

Front end mock

At present, the development mode is generally separated from the front end and the back end, so it is inevitable to “accommodate” each other. For example, the background only sets the interface documents generally, and the interface has not been released yet. As the front end, we can’t wait foolishly, but we can’t take care of many details without joint debugging. It’s easy to release the interface when it’s close to handover (we can’t narrowly think that the background deliberately, It’s just food). When the joint commissioning, many problems are found. It’s too embarrassing. If it’s delayed, the pot will easily cover the head of the front end. You have to think about a way:

  • “Please” the backstage to speed up and ensure the quality. This is a way. Please entrust it every time, please( There are often no eggs for peace of mind…)
  • Their own mock interface, better “asynchronous” development with the background, quickly promote the front-end work progress, expose problems as soon as possible, and strive for more time to solve them.

How to use mock

Install firstmockjs

    yarn add -D mockjs

Then take a look at what your network request library uses:

__axios__:

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

__ fetch__: You have to deal with it

Install firstmockjs-fetch

    yarn add -D mockjs-fetch

then

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

That’s the basic operation, but it’s not enough.


How to use mock gracefully

I’ve seen a lot of projects, often writing a pile of…. 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 learn about it on the official website. This is not important. We mainly focus on codereview
      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 comment. I don’t know if it’s my “aesthetic” strange. I think this code is a little awkward.

Codereview:

  1. First, the head is introducedmockjs
  2. Then we introduced two tool functions. Let’s do nothing first

    import { builder, getBody } from '../util'
  3. Mock.mock(/\/auth\/login/, 'post', login)Then the mock is executed

__ Evaluation _:

  1. EM ~ ~ ~, quote every mock module you writemockjsLibrary, repeat, although there is only one__ But I can bear it.
  2. EM ~ ~ ~, why do you need to introduce tool functions? Why do you need to understand tool functions? Or two! In order to realize the function beyond the basic mock, it can’t be said, but it isSimple mock, it’s kind of__ It’s unbearable.
  3. what!!!, The interface address of mock is actually “hard”. Think about the fear dominated by hard coding, it’s simply__ Can’t bear, can’t bear _!!!

__ Summary _:

Repeat (even if there are only a few), pay attention to many points (even if there are only a few), hard coding (even if there is only one place), and we can’t bear it if we have the ability to reconstruct. We just want to mock the data. It’s not good to point directly. Just like literally, I want to “mock” 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 })

Then the expected look of mock should be as follows:

import BaseMock from './baseMock'

let config = {
    fetchLightAdd: {
       ...
    },
    fetchLightUpdate: {
       ...
    },
    fetchLightDetail: (data) => {
        const { body = {} } = data;
        let params = JSON.parse(body);
        //Here, different results are given for various simulation input conditions.
        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 review codereview again:

  1. First of all, mockjs is introduced into each file: to solve the problem, EM ~ ~ ~ is just introduced insteadBaseMock(originally, I wanted to save this sentence, but I was worried that the code would not be easy to understand, or I would almost draw a knife)
  2. Multiple concerns: solution
  3. Hard coding: Solving

__ Summary _: It’s a simple data structure. It’s provided to you. It’s finished. If you want to mock which interface, write the interface name. It’s really literal: I think “mock” is an “API”. Others don’t need your attention. It’s so simple and natural.


Don’t forget that mock is only used in development mode.

Dynamic introduction according to the environment:

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

It’s not good to remove the package when publishing and packaging. Is it small

Options for configuring webpak:

//Isenvproduction process.env.node_ From envde value judgment
 externals:isEnvProduction?{
            mockjs:mockjs
 }:{}

Let’s see:

First of all, the packaging speed of moderate is still very fast, only 21s, hehe
Mock is both a shield and a weapon

Then look at the report:
Mock is both a shield and a weapon


epilogue

It’s better to ask others than to ask yourself. Mock can really relieve a lot of pressure. It’s not easy at the front end. TA’s difficulty is not that kind of ~ ~ ~ difficulty. TA is really that kind, that kind of rare kind, the same difficulty as neuropathy.

Mock is both a shield and a weapon

Ideological

Recommended Today

(7) Introduction and use of spring boot starter for Java spring cloud enterprise rapid development architecture

​The convenience of spring boot is reflected in that it simplifies many cumbersome configurations, which is a blessing for developers. By introducing various spring boot starter packages, you can quickly build a scaffold for a project and recommend the source code of distributed architecture. The spring boot starter package currently available includes: Spring boot starter […]