Mockjs profile

Mock.js is a simulation data generator to help the front-end to develop and prototype separate from the back-end progress and reduce some monotony particularly while writing automated tests.

Mock.js is a Mock data generator that helps to separate front-end development and prototyping from back-end processes, reducing some of the monotony, especially when writing automated tests.

The installation

yarn : yarn add mockjs

npm: npm i mockjs

The sample

  var Mock = require('mockjs')
  // Then simulate a list with a length of 1-10 and an increasing id
  var data = Mock.mock({
      'list|1-10': [{
          'id|+1': 1}]})// Output result -> {list:[]} List is 1 to 10 characters in length, and the ids are incremented from 1
  console.log(JSON.stringify(data, null.4))
Copy the code

Grammar specification

The syntax specification for mock.js consists of two parts:

  • Data Template Definition (DTD)
  • Data Placeholder Definition (DPD)

Data templates

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

  // Attribute name name
  // Generate rule rule
  // Attribute value value
  'name|rule': value
Copy the code

Note:

  • Use | space between the attribute name and generate rules.
  • The generation rule is optional.
  • There are seven formats for generating rules:
    1. 'name|min-max': value
    2. 'name|count': value
    3. 'name|min-max.dmin-dmax': value
    4. 'name|min-max.dcount': value
    5. 'name|count.dmin-dmax': value
    6. 'name|count.dcount': value
    7. 'name|+step': value
  • The meaning of the generation rule depends on the attribute value.
  • Attribute values can contain @ placeholders.
  • The property value also specifies the initial value and type of the final value.

Generation rules and examples:

  • The attribute value is a String

    • ‘name | min – Max’ : ‘value’ by repeating ‘value’ to generate a string, repeat number greater than or equal to the min, less than or equal to Max.
    • ‘name | count’ : ‘value’ by repeating ‘value’ to generate a string, repetition frequency is equal to the count.
      Mock.mock({ 'name|2': 'value' }) // {name:valuevalue}
    Copy the code
  • The attribute value is the Number

    • ‘name | + 1’ : 100 automatically add 1 attribute values, the initial value is 100
    • ‘name | 1-100:100 generated an integer greater than or equal to 1 and less than or equal to 100, 100 only to determine the type of attribute values.
    • ‘name | 1-100.1-10:100 generated a floating point number, the integer part is greater than or equal to 1, 100, less than or equal to the decimal part keep 1 to 10.
      {
          'the number1 | 1-100.1-10': 1.'number2 | 123.1-10': 1.'number3 | 123.3': 1.'number4 | 123.10': 1.123
      }
      / / = >
      {
          "number1": 12.92."number2": 123.51."number3": 123.777."number4": 123.1231091814
      }
    Copy the code
  • Attribute values are Boolean

    • The name ‘| 1’ : the value randomly generated a Boolean value, the probability that the value is true is 1/2, the probability of a false value is 1/2.
    • ‘name | min – Max’ : the value randomly generated a Boolean value, the value of the value of the probability is min / + Max (min), value of! The probability of value is Max over min plus Max.
      Mock.mock({ 'name|1': true }) // {name:true} // The probability of true or false is 50/50
    Copy the code
  • An attribute value is an Object

    • ‘name | min – Max’ : {} {} property values in the random min to the Max attribute.
    • ‘name | count’ : {} {} property values in the random count attribute.
      Mock.mock({ 'name|1': { a: 1.f: 1.b: 2.v: 3}})// {name:{a:1}} random a\f\b\v attribute
    Copy the code
  • The value is an Array Array

    • ‘name|1’: [{}, {} …] Attribute value [{}, {}…] Is randomly selected as the final value.
    • ‘name|min-max’: [{}, {} …] By repeating the attribute values [{}, {}…] Generates a new array, repeated more than min and less than Max.
    • ‘name|count’: [{}, {} …] By repeating the attribute values [{}, {}…] Generates a new array, repeated count.
  • An attribute value is an array Function

    • ‘name’: function(){} Executes function(){}, taking its return value as the final property value, in the context of the object on which ‘name’ resides.
      function test() {
        return 2
      }
      data = Mock.mock({ 'name': test() }) // {name:2}
    Copy the code

Data placeholders

Placeholders simply take a place in the attribute value string and do not appear in the final attribute value. The format of the placeholders is:

@ placeholder @ placeholder (parameter [, parameter])Copy the code

Note:

  • The @ sign indicates that the string following it is a placeholder.
  • Placeholders refer to methods in mock. Random.
  • Extend custom placeholders with mock.random.extend ().
  • Placeholders can also refer to properties in the data template.
  • Placeholders refer to attributes in the data template in preference.

Uppercase placeholders are the recommended encoding style to improve the visual recognition of placeholders when reading and to quickly identify placeholders and ordinary characters.


  {
      name: {
          first: '@FIRST'.middle: '@FIRST'.last: '@LAST'.full: '@first @middle @last'}}/ / = >
  {
      "name": {
          "first": "Charles"."middle": "Brenda"."last": "Lopez"."full": "Charles Brenda Lopez"}}Copy the code

Practical API

To list some common front-end apis, see the documentation for more

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

Mock.mock( template )

Generate simulated data from the data template.

Mock.mock( rurl, template )

Record the data template. When an Ajax request matching an RURL is intercepted, mock data is generated from the data template and returned as response data.

The meanings and default values of the parameters are as follows:

Parameter rURL: Optional. Indicates the URL to be intercepted. It can be a URL string or A URL re. Json /, ‘/domian/list.json’. Parameter rtype: Optional. Represents the type of Ajax request to intercept. For example, GET, POST, PUT, and DELETE. Parameter template: Optional. Represents a data template, which can be an object or a string. Data such as {‘ | 1-10 ‘: [] {}},’ @ EMAIL ‘. Parameter function(options) : Optional. Represents the function used to generate the response data. Options: Points to the set of Ajax options for this request.

Mock.Random

Mock.Random is a utility class for generating various Random data. Mock.Random’s methods are called “placeholders” in the data template and are referenced in the @ placeholder format (parameter [, parameter]). Such as:

  var Random = Mock.Random;
  Random.email() // => "[email protected]"
  Mock.mock('@EMAIL') // => "[email protected]"
  Mock.mock( { email: '@EMAIL'})// => { email: "[email protected]" }
Copy the code

Mock.Random provides the following complete method (placeholder) :

Type Method
Basics boolean, natural, integer, float, character, string, range, date, time, datetime, now
Image image, dataImage
Color color
Text paragraph, sentence, word, title
Name first, last, name
Web url, domain, email, ip, tld
Address area, region
Helpers capitalize, upper, lower, pick, shuffle
Miscellaneous guid, id

Methods in Mock.Random correspond one-to-one to the @ placeholder of the data template, and you can extend methods for Mock.Random if needed, and then reference them in the data template via the @ extension method. Such as:

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

More and more

Mockjs official document

Mockjs example of Ajax interception