preface

There must be a lot of front-end procedures ape very leisurely before the joint adjustment 😌, but the joint adjustment stage continued to work overtime, until the test, online.

This reason is nothing more than the demand is not clear and other reasons, but if we can finish most of the work before the joint investigation, I believe that we can leave work on time 🚘. If you suffer from a similar phenomenon, I hope to finish reading this article, perhaps freeing you from the uncoordinated work.

You can add favorites (Ctrl + D or Command + D) in case you need them.


background

In a development environment, the backend is developed in parallel with the front end, or the front end needs to wait for the background interface development. The interface is directly heavily dependent and the business logic of generating data is complicated, which seriously affects the development efficiency.

So it’s important to learn how to use Mock data that works best for you.

Here are some common mock schemes. By learning how to automate mocks, reduce rework and reduce real tuning problems, you can choose and configure the most appropriate scheme for your development scenario.


Common MOCK scheme descriptions

1. Code intrusion (most commonly used in real development, but not recommended)

Features: Kill Mock data directly in code, or request a local JSON file

  1. Mock is not as good as other schemes
  2. Switching to a real Server environment is cumbersome, and anything that requires hacking into the code switching environment is not good

2. Request interception [MOCKJS]

Rep: Mock. Js

Features:

  • By intercepting a specific AJAX request and generating random numbers of a given data type, you simulate the interface provided by the back-end classmate.
  • Using data template definition, random generation of definition data has a large degree of freedom. Use the MockJS Random utility class’s method definition, which has little freedom and can only randomize the data types provided by MockJS.
  • It is typically used in conjunction with other libraries, alone in a project, or through a reverse proxy.

Use format instructions:

Mock.mock( rurl? , rtype? , template|function( options ) )

  • Rurl: Optional, intercepting URL address, can be a string or re (common)
  • Rtype: Optional, intercepted request type, string (case sensitive, must be lowercase).
  • The template | function (options) : need to be intercepted, after the returned data. Template is usually a JSON object type. Function returns template on return, where option contains the requested oneurl,type 和 The body attribute
  • Mock. Mock returns the actual result of template.

A simple example shows:

Randomly generated color

Mock.mock('@color') 
"#f279ba"
Copy the code

Randomly generated mailbox

Mock.mock('@email')
"[email protected]"
Copy the code

Random IP generation

Mock. Mock (' @ 'IP) "44.122.28.106"Copy the code

Generate an area address randomly

Mock. Mock ('@region') "northeast"Copy the code

Can also randomly generate pictures (and can be sent to configure the size of the picture, color, etc.)

Random.image() 
Copy the code

Generate strings according to rules

/ / the number of specified range Mock. Mock ({" string | 1-10 ":" u "}) / / {after execution "string" : Painted "u"} / / random number is 1-10 '*' character string / / fixed quantity Mock Mock ({" string | 3 ":" * * "}) / / execution after {" string ":" * * * "} / / generates a specified number of '*' (sample 3) stringCopy the code

Generates numbers in the specified range

/ / integer Mock. Mock ({" number | 1-100 ": 100}) / / {after execution" number ": 84} / / generated within the scope of 1-100 number / / decimal Mock Mock ({" number | 1-100.1-10 ": 1}) / / {after execution" number ": 72.15917} // Generate numbers from 1 to 100, randomly reserving 1-10 decimal placesCopy the code

Generate a random number of objects

Mock. Mock ({" object | 2-4 ": {" 110000", "Beijing", "120000", "tianjin", "130000", "hebei province", "140000" : "Shanxi Province"}}) / / execution, random access objects in 2-4 {" object ": {" 120000", "tianjin", "130000", "hebei province"}}Copy the code

Generates the specified number of arrays

Mock. Mock ({" array | 1 ": [" AMD", "CMD", "UMD"]}) {" array ":" CMD "} / / a random access objectsCopy the code

Generating an array of objects

// List specifies the number of objects in the array, from a minimum of one to a maximum of 10. Mock. Mock ({/ / the list of attribute values is an array, containing 1 to 10 elements' list | 1-10 ': [{/ / attribute id is the one from the number, the starting value is 1, each time to add 1 + 1' | 'id: 1}]}) / / the result of random {" a list ": [{" id" : 1}, {2} "id" :]}Copy the code

.

See the official link for more examples

Grammar specification

> Data template definition

Define rules: ‘key | rules’ : the value

The data type of an attribute value can be Number, Boolean, String, Object, Array, Function, or Null, but not Undefined

'name|min-max': value 'name|count': value 'name|min-max.dmin-dmax': value 'name|min-max.dcount': The value of 'name | count. Dmin - on3dmax' : the value 'name | count. Dcount' : the value 'name | + step' : the value 'regexp: / \ d {5, 10} /,Copy the code

An example of an intercepting interface returned:

Mock. Mock (/notification\/count/, {"code": 200, "MSG ": "success", "data": { "count": 3 } }) 2. Other optimizations can be made by introducing mocks in the entry: add commands and mock environment variables to the NPM script that the development environment launches with. Use mock environment variables in the entry file to determine whether to load mock.js, separating mock data from business code completely.Copy the code

> View and use Random

  1. The global
NPM install mockjs -g random -h views available templatesCopy the code
  1. Local use

Randomly generated data

Mock. Mock ({email: ‘@email’}) placeholder is equivalent to calling mock.random.email () to generate Random emails.

Can also randomly generate pictures, color, address, url, self-increment, etc.

  1. Extension template
Random.extend({ constellation: Function (date) {var constellations = [' Aries', 'Taurus',' Gemini ', 'cancer', 'Leo, virgo, libra, Scorpio, Sagittarius, Capricorn, Aquarius, 'Pisces '] return this. Pick (constellations)}})Copy the code

> Mock. Valid (template, data) verifies data

var tempObj = { "user|1-3" : [{'name':'@name', 'id|28-338': 88}] }; Var realData = {" user ": [{' name ':' zhang ', 'id' : 90}]}. // If the verification passes, null data is returned. If the verification fails, the cause is returned. Console. log(Mock. Valid (tempObj,realData)); console.log(Mock.Copy the code

> Mock.toJSONSchema( template )

Convert the mock. js-style data template template to JSON Schema.

> Mock.setup( settings )

Configure the behavior when intercepting Ajax requests. The configuration items supported are timeout.

Mock.setup({
    timeout: 400
})
Mock.setup({
    timeout: '200-600'
})
Copy the code

The advantages and disadvantages (MOCKJS)

Advantages:

  1. Separate from the front-end code
  2. Generate random data

Disadvantages:

  1. Data are dynamically generated fake data, can not simulate the real add, delete, change and check situation
  2. Only Ajax is supported, not FETCH

3. Interface management tool

On behalf of:

rap(Ali, has stopped maintenance, using RAP2)
swagger
moco(reference, similar to the front-end processing mock, json dummy data + service)
yapi(Qunar development)

Advantages and disadvantages (Interface management tool)

Advantages:

  1. Configuration powerful, interface management and Mock integrated, back-end modify interface Mock also changes, reliable
  2. Unified interface management background, easy to find and use.

Disadvantages:

  1. The configuration is complex and depends on the back end. The back end may be unwilling to make a move, or the interface may be developed after the configuration is finished. Mock data are all controlled by the background, and the front end students basically cannot make efforts in any abnormal situation. There is the principle of separation of back, front and background.
  2. It is generally used as infrastructure for large teams, but should be considered carefully if it is not
  3. Instead of having the backend handle mock data-related issues, it’s better to speed up the delivery of real interface data.

4. Local Node server

Json-server Principle: Use LowDB to operate small local databases (following REST APIS). Features:

  • It can be used independently or as middleware for Node servicesserver.use(db) 
  • Db can be a JSON file (more intuitive) or a JS file (more flexible)
  • You can set cross-domain, enable GZIP, set delay, log, and specify routes.json-server [options] <source> 
  • Can be command-line started orjson-server.jsonDirectly start after the configuration
  • You can customize route mappings (key for real routes and value for mock routes)

Easy implementation of background functions

Filter: GET /list? Name. The age = 18; Paging: / users? _page=3&_limit=5 sort: /users? _sort=id&_order=desc delimited: /users? _start=2&_end=5 operation: select a range using _gte or _lte, exclude a value using _ne, and use _like for fuzzy lookup (regular expression support)......Copy the code

Service management

Add, delete, change see postman example. (Note that body-raw should select JSON mode)

Advantages:

  1. Simple configuration, jSON-Server can even start a REST API Server in 30 seconds
  2. High degree of customization, everything is under control
  3. Add delete change check real simulation

Disadvantages:

  1. In contrast to interface management tools, this cannot be automatically modified as the back-end API changes

5. Packet capture tool

Use Charles, Fiddler and other agent tools, common processing methods are

  • Map urls to local files; (Debugging APP mixed development, etc.)
  • Debugger a URL that modifies the response data.
  • Intercept and return local data, such asCharles,You can use Map locale or Map Remote.
  1. Right click on the URL, copy Response
  2. Create new mock JSON data locally and paste the response to modify it
  3. Visit the URL again and observe the API changes.
The advantages and disadvantages:

Advantages: Mock facilitates mixed development troubleshooting, online troubleshooting, etc. Disadvantages: debugging is relatively tedious.

6. Combination mode

Easy – Mock (provides online service and interface proxy, supports MockJS, Swagger, restAPI style) Node framework generator + JSON-server + MockJS

REST API

URI on behalf of the resource/object, the METHOD represents the behavior www.ruanyifeng.com/blog/2014/0…

GET /tickets/ / list GET /tickets/12 // details POST /tickets/ / add PUT /tickets/12 // replace PATCH /tickets/12 // modify DELETE /tickets/12 // delete resource negative names represent the set of resources for the corresponding table, method verbs.Copy the code
  • pointITo understandpatch vs put

The last

If you find it helpful, you can like it and support it. If you have any questions or suggestions, please leave them at 👇🏻. Thank you very much.

See my previous article on how Javascript can take over XHR requests