What is a Mock?

During debugging, for some data that is not easy to construct/obtain, follow the rules to create a dummy data to get through the process.

For example, using mock. js, randomly generate a string of asterisks between 1 and 10 in length.

Mock. Js is a Mock toolkit for Javascript syntax. Java Mock tools include EasyMock, mockito, etc.

What does a Mock do?

1. The API is not well developed, so Mock is used for quick docking

After the product manager issued the requirements, the front and back end students first produced an API document according to the functional requirements, and then developed in parallel according to the API document.

How do you develop the front end independently of the back end without relying on it to provide the data?

With mocks, you can build mocks into your development environment code, intercept requests, and simulate real API returns. If your company is using an interface management platform, you can also use the platform to generate Mock apis for documentation when it is published.

2. Provide data for testing

Mock Mock data instead of the parts we want to control that are difficult to control

For example,

  • Some apis rely on the return values of other apis. Use mocks to easily change the return values and test the PERFORMANCE of apis in different scenarios.
  • An API is so slow that you can temporarily Mock it out to quickly tune the entire scenario testing process.

3. Convenient and quick establishment of functional prototypes

Adapting requirements is common in agile development. Mocks can be used to quickly build functional prototypes, visualize business logic, facilitate product adjustment requirements, and demonstrate the system with fake data.

The Mock deployment

Note the following three options, each with its own merits.

1. Where do I write Mock values as variables

For example,

advantages

  • Low cost, easy to use, only need to learn Mock. Js template syntax.
  • It is not affected by networks.
  • Mocks can be changed to see the effect quickly.

disadvantages

  • Mock code is highly coupled to business code, and it is easy to miss the test code when it goes online, laying a hidden mine for the code.
  • Unable to respond quickly to document changes and keep the Mock return data consistent with the document.
  • Only front-end developers can Mock, not work with other departments.
  • No API request, not real enough.

2. Mock.js intercepts requests

Mock. Mock intercepts the request

var data = Mock.mock("https://www.baidu.com", {
    "string|1-10": "★".// Randomly generate 1 to 10 strings "★"
})
var request = new XMLHttpRequest();
request.open("GET"."https://www.baidu.com".true);
request.send();
request.onreadystatechange = function () {
    if (request.readyState === 4 && request.status === 200) {
        console.log(request.responseText)
    }
}
Copy the code

Console output

advantages

  • Mock. Js template syntax, Mock.
  • It is not affected by networks.
  • Mocks can be changed to see the effect quickly.

disadvantages

  • For RESTful apis, you need to write a re to match the request address.
  • The Mock code is still coupled to the business code, so you can have a separate Mock folder and build online without packing the business code.
  • Unable to respond quickly to document changes and keep the Mock data consistent with the document;
  • The API request was Mock intercepted and not actually sent, not real enough.
  • Only front-end developers can Mock, not work with other departments.

3. Mock Server

No different from the actual request HTTP API, the API response value is not the actual data fetched from the database, but the Mock generated fake data.

advantages

  • Quick Mock changes based on synchronous document changes, fast response!
  • Synergies allow testers to build unit tests ahead of time using mocks created by development.
  • With tools, Mock data can be managed through the user interface.

disadvantages

  • It costs money (money to deploy the server or Sass fees)
  • You need to choose the right tool, otherwise the efficiency of using the tool will not keep pace with the rate at which you find bugs
  • If you are a Mock Server deployed on your own Server, the front end cannot change the Mock values quickly. With locally deployed Mock Servers, multiple front ends cannot share data at the same time.

Their structures,

For a variety of language deployment scheme tutorial rich, examples do not cite, their own search.

Platform deployment

Eolinker

Online site, no deployment is required. The free version supports three-person collaboration, and more than three people need to sign up for the paid version.

You can manage API documents, and the Mock function provided by the system can quickly generate random data from the API document return value information. Support to set trigger conditions (request header, request body), according to different trigger conditions to get different return values.

Easy Mock

Not used, support online (the online version may not be stable), also support local deployment.

Mock data generation specification

You can tell a Mock how to generate data in two ways: a custom rule data template, or a placeholder that provides common random values such as · picture, email, name, and so on.

1. Data Template Definition (DTD)

To start with an example, the Mock. Mock function generates JSON from the corresponding data template.

Mock.mock({
 "string|1-10": "★".// Randomly generate 1 to 10 strings "★"
 "string2|3": "★".// Fixed generating 3 strings "★"
 "number|+1": 202.// Each request increments by 1, with an initial value of 202
 "Number2 | 1-100.1-10": 1.// Generate a floating point number with integer parts 1-100 and decimal parts 1-10 bits reserved. The attribute value number is used only to determine the type.
 "boolean|1-2": true.// The probability of true is 1/(1+2), and the probability of false is also 2/3.
 "regexp": /[a-z][A-Z][0-9]/.// Randomly generate a string that satisfies the re
 "object|2": {
   "310000": "Shanghai"."320000": Jiangsu Province."440000":"Guangdong province"
 },// Randomly select two attributes from the object to generate the object
 "array|1": [ "AMD"."CMD"].// Select a random element from the array to generate a value
 "arrayRepeat|3": ["AMD"."CMD"].// Repeat the array element 3 times to generate the array
 "date":"@date"// Generate a random date
})
Copy the code

Generate results

{
 "string": Painted "u"."string2": Painted painted "u"."number": 202."number2": 71.73566."boolean":true."regexp": "qS8"."absolutePath": Painted painted "demo"."object": {
   "310000": "Shanghai"."440000": "Guangdong province"
 },
 "array": "AMD"."arrayRepeat": ["AMD"."CMD"."AMD"."CMD",AMD","CMD"]."date":"1980- 12- 19"}Copy the code

Each attribute in the data template consists of three parts: attribute name, generation rule, and attribute value:

/ / 'attribute name | rules: attribute values
'name|rule': value
Copy the code

The attribute name is the parameter name, and the generation rule and the attribute value together determine the generated parameter value.

{
//" parameter ":" parameter value"
  "string": Painted "u"
}
Copy the code

For different attribute value types, generation rules have different meanings. Some generation rules are probability (Boolean), and some generation rules are repetition. Refer to the official mock.js documentation for details

2. Data Placeholder Definition (DPD)

Placeholders are mocks that provide common random data such as randomly generated images, email addresses, and names.

Usage 1: Use directly

Mock.mock('@date')/ / 1982-10-15
Mock.Random.date()/ / 1997-12-31
Copy the code

Usage 2: Used in data templates

 Mock.mock({
  "date":"@date".// Random date
  "float":"@float".// Random floating point number
  "name":"xxxx"./ / a fixed value
  "quoteStrin1": "@name".// Reference other attributes
  "user": {
    "name": "demo"
  },/ / a fixed value
  "quoteString": "@user/name".// Reference other attributes
 })
Copy the code
{
    "date":"2020-06-29"."float":2202285915843574.5."name":"xxxx"."quoteStrin1":"xxxx"."user ": {"name":"demo"
    },
    "quoteString":"demo"
}
Copy the code

Note that if the referenced property name is the same as the Mock placeholder name (quoteStrin1 in the above example), the reference value takes precedence over the placeholder, so the final quoteStrin1 property value is the same as the property value of the name property, not the value generated by the placeholder (Paul Miller).

A Mock function

1.Mock.mock

Intercept the request and generate mock data

var data = Mock.mock("https://www.baidu.com", {
    "string|1-10": "★".// Randomly generate 1 to 10 strings "★"
})
var request = new XMLHttpRequest();
request.open("GET"."https://www.baidu.com".true);
request.send();
request.onreadystatechange = function () {
    if (request.readyState === 4 && request.status === 200) {
        console.log(request.responseText)
    }
}
Copy the code

Generate simulation data directly

var data = Mock.mock("https://www.baidu.com", {
    "string|1-10": "★".// Randomly generate 1 to 10 strings "★"
})
Painted / / {" string ", "u"}
Copy the code

2.Mock.Random

Mock.Random is a utility class for generating various Random data. Mock.Random provides the following complete method:

type methods note
Basic boolean, natural, integer, float, character, string, range
Date date,time, datetime, now
Image image, dataImage Generate image address
Color color,hex,rgb,rgba,hsl
Text paragraph, sentence, word, title, cparagraph, csentence, cword, ctitle
Name first, last, name, cfirst, clast, cname
Web url, domain,protocol, email, ip, tld
Address region,province,city,county,zip
Helper capitalize, upper, lower, pick, shuffle Method, the Mock. Mock (‘ @ the lower (” HELLO “) ‘) – > HELLO
Miscellaneous uuid,guid, id,increment

You can also use Random. Extend to extend placeholders.

Random.extend({
    constellation: function(date) {
        var constellations = ['Aries'.'Taurus'.'Gemini'.'Cancer'.'狮子座'.'Virgo'.'Libra'.'Scorpio'.Sagittarius.'Capricorn'.'Aquarius'.'Pisces']
        return this.pick(constellations)
    }
})
Random.constellation()
// => "Aquarius"
Mock.mock('@CONSTELLATION')
// => "Scorpio"
Mock.mock({
    constellation: '@CONSTELLATION'
})
// => {constellation: "Sagittarius"}
Copy the code

quiz

Use the Mock to generate objects with the following logic

{
    "status":200.// One of 200, 300, or 500
    "boolean":true.// The probability of true is 1/4, and the probability of false is 3/4
    "name":"Plum Dog eggs"// Random Chinese name
}
Copy the code

The resources

  • The Mock. Js document

  • No API? No Problem! Rapid Development via Mock APIs-Cory House

  • Mo Chi Yu – How do you build a Web front-end Mock Server?