Static JSON is not enough for the front-end. It is time to use mock.js, the syntax used by many online mock apis
The Mock. Introduction of js
Mock.js is a Mock data generator designed to help front-end attackers develop independently of the back-end and to help write unit tests.
Example: mockjs.com/examples.ht… Documents: mockjs.com/0.1/
Function:
- Generate simulated data based on data template;
- Type rich random data
- Mock Ajax requests
Personal application:
Local services built using Koa and MockJS
Personal repository: Mock – Server, out of the box, like can star ^ _ ^
Grammar specification
The syntax specification for mock.js consists of two parts:
- Data Template Definition (DTD)
- Data Placeholder Definition (DPD)
Data templates define DTDS
Each attribute in the data template consists of three parts: attribute name, generation rule, and attribute value:
Attribute name | generate rules: attribute values' name | 'rule: the valueCopy the code
Generate rules
-
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 Copy the code
-
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.
String: The attribute value is a String
'name|min-max': string
Repeated string String Generates a string. The number of repeated times is greater than or equal to min and less than or equal to Max
/ / generated 1 ~ 10 "u" is the Mock. Mock ({" string | 1-10 ":" u "}) / / = = > {" string ":" u u u u "}Copy the code
'name|count': string
Repeated string string generates a string repeated times equal to count
/ / repeat. "String" three Mock Mock ({" String | 3 ":" String ",}) / / = = > {" String ":" StringStringString}"Copy the code
Number: The value of the attribute is a Number
'name|min-max': number
Generate an integer that is greater than or equal to min and less than or equal to Max. The value of number is used only to determine the number type
: / / generates an integer, interval [1, 10] Mock. Mock ({" number | 1-10 ": 100}) / / = = > {6}" number ":Copy the code
'name|min-max.dmin-dmax': number
Generates a floating point Number, the integer part is greater than or equal to min, less than or equal to Max, the decimal part is reserved from dmin to dmax bits, and the attribute value value is used only to determine the Number type
// number1: generates a decimal number, the integer range: [1,10], reserving 2 to 4 decimal places // number2: generates a decimal number, reserving 2 to 4 decimal places // number3: generates a decimal number, reserving 10 decimal places, reserving 2 to 4 decimal places // number3: , generate a decimal integer part of 10, the decimal part keep two Mock. Mock ({" number1 | 1-10.2-4 ", 100, "number2 | 10.2-4", 100, "number3 | 10.2" : 100,}) / / = > {" number1 ": 6.123," number2 ": 10.2884," number3 ": 10.68,}Copy the code
'name|+step': number
The value of the attribute is incremented by step, and the initial value is number. Step cannot be negative
The refresh rule for “Number” is not clear. The refresh rule for “Result” is not clear. The refresh rule for “Number” is clear.
/ / generates an array list, each item id on the 5, the initial value for 100 Mock. Mock ({" list | 3 ": [{" id | + 5" : 100}],}) / / = > {" a list ": [{id: 100}, {id: 105}, {id: 110}, ]}Copy the code
Boolean: The property value isBoolean value
'name|1': boolean
Generate a random Boolean value with a probability of 1/2 true and 1/2 false
/ / generates a Boolean value, 1/2 to true, 1/2 to false Mock the Mock ({" Boolean | 1 ": true,}) / / = > {}" Boolean ": falseCopy the code
'name|min-max': boolean
Generates a random Boolean value with a Boolean probability of min/(min + Max) with a value of! Boolean probability is Max/(min + Max)
/ / generates a Boolean value, a third to false, two-thirds to true Mock the Mock ({" Boolean | 1-2 ": false,}) / / = > {}" Boolean ": falseCopy the code
Object: The property value is an ObjectObject
'name|min-max': object
Randomly select min to Max attributes from the attribute value object.
/ / generates an object that contains 1 ~ 2 attributes Mock. Mock ({" object | 1-2 ": {" name" : "code", "gender" : 1, "age" : 18, "tel" : "18911112222" } }) // => {object: { "name": "code", }}Copy the code
'name|count': object
Select count randomly from the attribute value object.
/ / generates an object that contains two attributes Mock. Mock ({" object | 2 ": {" name" : "code", "gender" : 1, "age" : 18, "tel" : "18911112222" } }) // => {object: { "name": "code", "age": 18, }}Copy the code
Array: The property value is an Array
'name|1': array
One element is randomly selected from array as the final value
Mock. Mock ({" array | 1 ": [1, 2, 3, 4]}) / / = > {array: 1}Copy the code
'name|count': array
Generates a new array by repeating the property value array, count times
The Mock. Mock ({" array1 | 2 ": [1, 2, 3]," array2 | 2 ": [{a: 1}, 2],}) / / = > {array1: [1, 2, 3, 1, 2, 3], array2: [ {a:1}, 2, {a:1}, 2 ] }Copy the code
- `’name|min-max’: array
Generates a new array by repeating the property value array more than min and less than Max
Mock.mock({
"array|1-3": [{id:1, name: 2}],
})
// =>
{array1: [
{id:1, name: 2},
{id:1, name: 2}
]}
Copy the code
'name|+step': array
Loops through the elements of array at index 0, incrementing the index by step and mod array.length
Mock. Mock ({" array | 4 ": [{" number | + 1" : [2, 4]}]}) / / = > {array: [{number: 2}, {number: 4}, {2} number:, {number: 4}]}Copy the code
Function: Attribute value is a Function
'name': function(){}
Take the return value of the function as the final property value, in the context of the object in which ‘name’ resides.
Mock.mock({ 'firstName': 'Guoda', 'name': function() { var nameObj = Mock.mock({ 'firstName': 'Jason', 'lastName': 'Statham', 'name': This. FirstName + "" +this.lastName; // This. } }) return nameObj.name } }) // => { "firstName": "Guoda", "name": "Jason Statham" }Copy the code
RegExp: The property value is a regular expression
'name': regexp
Mock. Mock ({' regexp1: / [a-z] [a-z] / [0-9], 'regexp2: / \ d {5, 10} /' regexp3 | 1-5 ': / \ d {5, 10} \ - /,' regexp4 | 3 ': \ * / / \ d {2, 4}}) / / = > {" regexp1 ":" cD3, "" regexp2" : "54833", "regexp3" : "597425-8412964-5862207-7615212-051289-582018-", "regexp4": "374*1397*88*027*", }Copy the code
Path: The attribute value is obtained from the Path
- Relative Path Relative Path
Path relative to the current property name
var relativePathData = Mock.mock({ "foo": "Hello", "nested": { "a": { "b": { "c": "Mock.js" } } }, "relativePath": { "a": { "b": { "c": "@.. /.. /.. /foo @.. /.. /.. /nested/a/b/c" } } } }) console.log(relativePathData.relativePath) // => "Hello Mock.js"Copy the code
- Absolute Path Absolute Path
The outermost layer is the root path
var absolutePathData = Mock.mock({
"foo": "Hello",
"nested": {
"a": {
"b": {
"c": "Mock.js"
}
}
},
"absolutePath": "@/foo @/nested/a/b/c"
})
console.log(absolutePathData.absolutePath)
// =>
"Hello Mock.js"
Copy the code
Data placeholders define DPD
Placeholders simply take a place in the attribute value string and do not appear in the final attribute value
- The @ sign indicates that the string following it is a placeholder
- The placeholder refers to
Mock.Random
It is recommended that the method name be quoted in all uppercase, in order to improve the visual recognition of placeholders when reading, and quickly identify placeholders and common characters - through
Mock.Random.extend()
To extend custom placeholders - Placeholders can also refer to properties in the data template
- Placeholders refer to attributes in the data template in preference
- A placeholdersupportRelative paths 和 An absolute path.
Mock. Mock ({"name": {FIRST:); // Both @first and @first can call mock.random.first (). '@first ', // @first references mock.random.first () last:' @last ', // @last references mock.random.last () full: '@ first @ last' / / @ first priority to the reference data template attribute (this. First)}}) / / = > {" name ": {" first" : "Charles" and "last", "Lopez", "full" : "Charles Lopez" }}Copy the code
Composite sample
Mock.mock({ "list|10": [ { "id": "@GUID", "first": "@CFIRST", "last": "@CLAST", "name": "@first@last", "age|10-60": 1, "gender" : "@ pick ([1, 2])", "say:" the function () {return "my name is" + enclosing name;}}]})Copy the code
Mock.Random
Mock.Random is a utility class that generates Random data in one of two ways:
Var random = Mock.Random; Random.boolean() Random.boolean(1, 9, true) // 2. Mock ('@boolean()') Mock. Mock ('@boolean()') Mock. Mock ('@boolean(1, 9, true)')Copy the code
Custom placeholders
// Custom placeholder mock.random.extend ({constellations: [' Aries, Taurus, Gemini, cancer, Leo, virgo, libra, Scorpio, Sagittarius, Capricorn, Aquarius, Pisces'], constellation: Function (date){return this.pick(this.constellations)}}) random.constellation () // =>" Mock. Mock (' @constellation ') // => "Scorpio" Mock. Mock ({CONSTELLATION: '@constellation '}) // => {CONSTELLATION: "Sagittarius"}Copy the code
Basics
Boolean: Indicates a Boolean value
Random.boolean(min? , max? , current?)
For the parameter description, see Data Template Definition -Boolean
A natural number (an integer greater than or equal to 0)
Random.natural( min? , max? )
Parameter min: Optional. Indicates the minimum value of a random natural number. The default value is 0.
Parameter Max: Optional. Indicates the minimum value of a random natural number. The default value is 9007199254740992.
Integer: an integer (including negative numbers)
Random.integer( min?, max? )
Parameter min: Optional. Indicates the minimum value of a random integer. The default value is -9007199254740992.
Parameter Max: Optional. Indicates the maximum value of a random integer. The default value is 9007199254740992.
Float: indicates the floating point number
Random.float( min? , max? , dmin? , dmax? )
Parameter min: Optional. The minimum value of the integer part. The default value is -9007199254740992.
Parameter Max: Optional. The maximum value of the integer part. The default value is 9007199254740992.
Parameter Dmin: Optional. The minimum number of digits of a fractional part. The default value is 0.
Parameter Dmin: Optional. The maximum number of decimal places. The default value is 17.
Character: a single character
Random.character( pool? )
Parameter Pool: Optional. A string. Represents a character pool from which a character will be selected to return.
If ‘lower’ or ‘upper’, ‘number’, ‘symbol’ is passed, it is selected from the built-in character pool.
If this parameter is not passed, a random character from ‘lower’ + ‘upper’ + ‘number’ + ‘symbol’ is returned.
Built-in character pool: the lower: "abcdefghijklmnopqrstuvwxyz," upper: "abcdefghijklmnopqrstuvwxyz", number: "0123456789", the symbol:! "" @ # $% ^ & * () []"Copy the code
String: string
Random.string( pool? , min? , max? )
Parameter Pool: Optional. A string. Sense as above character.
Parameter min: Optional. Minimum length of random string. The default value is 3.
Parameter Max: Optional. The maximum length of a random string. The default value is 7.
Range: array of integers
Random.range(stop)
One argument: represents the end value of the integer in the array (not included in the return value)
Random.range(start? , stop, step?)
Parameter start: optional. The starting value of an integer in an array. The default value is 0.
Parameter stop: Mandatory. The end value of an integer in the array (not included in the return value).
Parameter step: Optional. The step size between the integers in the array. The default value is 1.
/ / a parameter to the end. The Random range (10) / / = > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] / / the Random parameters. The range (3, 7) / / = > [3, 4, 5, 6] Random.range(1, 10, 2) // => [1, 3, 5, 7, 9] Random.range(1, 10, 3) // => [1, 4, 7]Copy the code
Date
Parameter Format: Optional. Format the generated date string. The default value is YYYY-MM-DD. For an optional value, see date-format
Date: indicates the date string
Random.date( format? )
Time: indicates the time string
Random.time(format?)
Datetime: a random date and time string
Random.datetime( format? )
Now: Current date and time string
Random.now( unit? , format? )
Parameter unit: Optional. Represents a unit of time used to format the current date and time.
The value can be “year”, “month”, “week”, “day”, “minute”, “second”, or “week”. The format is not configured by default.
Parameter Format: Optional. Indicates the format of the generated date and time strings. The default value is YYYY-MM-DD HH: MM :ss.
Random.now()
// => "2018-11-09 10:28:53"
// Ranndom.now( unit )
Random.now('year')
// => "2018-01-01 00:00:00"
Random.now('month')
// => "2018-11-01 00:00:00"
Random.now('week')
// => "2018-11-04 00:00:00"
Random.now('day')
// => "2018-11-09 00:00:00"
Random.now('hour')
// => "2018-11-09 20:00:00"
Random.now('minute')
// => "2018-11-09 20:08:00"
Random.now('second')
// => "2018-11-09 20:08:38"
// Ranndom.now( unit, format )
Random.now('day', 'yyyy-MM-dd HH:mm:ss SS')
// => "2018-11-09 00:00:00 000"
Copy the code
Image
Image: indicates the URL of an image
Random.image( size? , background? , foreground? , format? , text? )
Parameter size: Optional. Indicates the width and height of the picture in the format ‘width x height’. By default, one is read randomly from the following array
[
'300x250', '250x250', '240x400', '336x280', '180x150', '720x300', '468x60',
'234x60', '88x31', '120x90', '120x60', '120x240', '125x125', '728x90',
'160x600', '120x600', '300x600'
]
Copy the code
Background: Optional. The background color of the image (hexadecimal color). The default is ‘#000000’. Use English words (red, etc.) to indicate that colors are invalid
Parameter Foreground: Optional. The foreground of the picture (file). The default is ‘#FFFFFF’. Use English words (red, etc.) to indicate that colors are invalid
Parameter Format: Optional. Indicates the format of the picture. The default value is’ PNG ‘. Possible values include ‘PNG’, ‘GIF’, and ‘JPG’.
Parameter text: Optional. Indicates the text on the picture (invalid in Chinese). The default value is size (size eg: 200×100).
Random.image('200x100', '#FF0000', '#FFF', 'png', 'text')
// =>
"https://dummyimage.com/200x100/FF0000/FFF.png&text=text"
Copy the code
DataImage: Base64 image
Random.dataImage( size? , text? )
The background color of the image is random and the value range is referenced from BrandColors.net/.
Color
Color: ‘# RRGGBB’
Random.color()
Return hexadecimal color (‘#RRGGBB’)
hex : ‘#RRGGBB’
Random.hex()
Return hexadecimal color (‘#RRGGBB’)
RGB: ‘RGB (r, g, b)’
Random.rgb()
Rgba: ‘RGB (r, g, b, a)’
Random.rgba()
HSL: ‘HSL (h, s, l)’
Random.hsl()
Random.color() // => "#f279c3" Random.hex() // => "#7988f2" Random.rgb() // => "rgb(242, 184, 121) "the Random rgba () / / = >" rgba (242, 121, 164, 0.58) "Random. An HSL () / / = >" an HSL (286, 82, 71). ""Copy the code
Text
Paragraph: English paragraph (multiple sentences)
Random.paragraph( len )
Parameter len: Optional. Indicates the number of sentences in the text. The default value is a random number between 3 and 7.
Random.paragraph( min? , max? )
Parameter min: Optional. Indicates the minimum number of sentences in a text. The default value is 3.
Parameter Max: Optional. Indicates the maximum number of sentences in a text. The default value is 7.
Sentence: A sentence in English
Generate a random sentence, capitalize the first word.
Random.sentence( len )
Parameter len: Optional. Indicates the number of words in a sentence. The default value is a random number between 12 and 18.
Random.sentence( min? , max? )
Parameter min: Optional. Indicates the minimum number of words in a sentence. The default value is 12.
Parameter Max: Optional. Indicates the maximum number of words in a sentence. The default value is 18.
Word: English word
Random.word( len )
Parameter len: Optional. Indicates the number of characters in a word. The default value is a random number between 3 and 10.
Random.word( min? , max? )
Parameter min: Optional. Indicates the minimum number of characters in a word. The default value is 3.
Parameter Max: Optional. Indicates the maximum number of characters in a word. The default value is 10.
Random.word()
// => "fzljqtu"
Copy the code
Title: the title
Generate a random title with the first letter of each word capitalized.
Random.title( len )
Parameter len: Optional. Indicates the number of words in the title. The default value is a random number between 3 and 7.
Random.title( min? , max? )
Parameter min: Optional. Indicates the minimum number of words in the title. The default value is 3.
Parameter Max: Optional. Indicates the maximum number of words in the title. The default value is 7.
Random.title()
// => "Odd Krdote Tidnsovvr Gcljiwzk Gtbckxopbg Vhfr"
Copy the code
Cparagraph: Chinese paragraph
Parameters with com.lowagie.text.paragraph
-
Random.cparagraph( len )
-
Random.cparagraph( min? , max? )
Random.cparagraph() // => Increase the old and new section of labor to geyuan mountain set total. But the Beijing eye as less empty is the original qi and knot. We have only done so and will do away with it.Copy the code
Csentence: Chinese sentence
Parameters with the sentence
Random.cparagraph( len )
Random.cparagraph( min? , max? )
Random. Csentence () // => "x = x = x"Copy the code
Cword: Chinese characters
The Random cword (pool)?
The Random cword (pool? , length?
Random.cword( pool? , min? , max? )
The Random cword (length)?
The Random cword (min and Max)
Parameter Pool: Optional. A string. Represents a pool of characters from which to return (repeatable selection) selected characters.
Parameter Length: Optional. Indicates the length of a random Chinese character. The default value is 1.
Parameter min: Optional. Indicates the minimum length of random Chinese characters.
Parameter Max: Optional. Indicates the maximum length of random Chinese characters.
// random.cword () random.cword () // random.cword (pool) random.cword (' zero one two three four five six seven eight ninety ') // => "ten" // Cword (pool, length) random.cword (pool, length) random.cword (pool, length) random.cword (pool, length) Cword (min, Max) Random. Cword (min, Max) Random. Cword (min, Max) Random. Max) Random. Cword (' 0, 2, 3, 4, 6, 7 ') // =>"Copy the code
Ctitle: Chinese title
The Random ctitle (length)?
The Random ctitle (min and Max)
Parameter Length: Optional. Indicates the length of random headings.
Parameter min: Optional. Indicates the minimum length of random headings, default is 3.
Parameter Max: Optional. Indicates the maximum length of a random header, which defaults to 7.
Random. Ctitle (3, 5) // =>"Copy the code
Name
First: English name
Random.first()
Randomly generate a common English name.
Last: English family name
Random.last()
Randomly generate a common English last name.
Name: English name
Random.name( middle? )
Randomly generate a common English name.
Parameter middle: Optional. Boolean value. Indicates whether a middle name is generated.
Random.name()
// => "Larry Wilson"
Random.name(true)
// => "Helen Carol Martinez"
Copy the code
Cfirst: Chinese family name
Random.cfirst()
Randomly generate a common Chinese surname.
Clast: Chinese name
Random.clast()
Randomly generate a common Chinese name.
Cname: Chinese name
Random.cname()
Random. Cname () // =>"Copy the code
Web
Url: indicates the URL address
Random.url()
Random.url()
// => "gopher://qmug.sh/uprwjbph"
Copy the code
Domain: the domain name
Random.domain()
Random.domain()
// => "ynadsh.tj"
Copy the code
Protocal: agreement
Random.protocol()
Random.protocol()
// => "http"
Copy the code
TLD: indicates the top-level domain name
Random.tld()
Random.tld()
// => "nz"
Copy the code
ip
Random.ip()
The Random. IP () / / = > "97.167.99.146"Copy the code
Email: email
Random.email()
Random.email()
// => "[email protected]"
Copy the code
Address
Region: regional
Random.region()
Generate a random (China) region.
Random. Area () // => "中 国"Copy the code
Province: a municipality, autonomous region, special administrative region
Random.province()
Random. City () // => "中 国"Copy the code
City: city
Random.city( prefix? )
Parameter prefix: Optional. Boolean value. Indicates whether the owning province is generated. The default value is false.
The Random city () / / = > "eastern city" is the Random. City (true) / / = > "jilin city of jilin province"Copy the code
-Blair: I’m in the county.
Random.county( prefix? )
Parameter prefix: Optional. Boolean value. Indicates whether a province or city is generated. The default value is false.
Random. County () // => "yongcheng county" Random. County (true) // => "Yongcheng County"Copy the code
Zip: indicates the zip code
Random.zip()
Randomly generate a zip code (six digits)
Random.zip()
// => "139862"
Copy the code
Helper: tool class
Capitalize: Capitalize
Random.capitalize( word )
Random.capitalize( 'hello' )
// => "Hello"
Copy the code
Upper: uppercase conversion
Random.upper( str )
Random.upper('hello WORld')
// => "HELLO WORLD"
Copy the code
Lower: lowercase conversion
Random.lower( str )
Random.lower('HELLO WorLD')
// => "hello world"
Copy the code
Pick: selects elements
Random.pick( arr )
Returns a random element from the array
Random.pick(['a', 'e', 'i', 'o', 'u'])
// => "o"
Copy the code
Shuffle: upset
Random.shuffle( arr )
Scrambles the order of the elements in the array and returns.
Random.shuffle(['a', 'e', 'i', 'o', 'u'])
// => ["i", "u", "a", "o", "e"]
Copy the code
Miscellaneous: Miscellaneous
Guid: random identifier
Random.guid()
Generate a GUID at random. The implementation of random.guid () references the UUID specification.
Random.guid()
// => "8Dc8DA10-3FDe-FFc8-3AD6-703bdeFff0D8"
Copy the code
Id: 18-digit ID card.
Random.id()
// Randomly generate an 18-bit id card. Random.id() // => "620000201010107263"Copy the code
Increment: indicates an incremented integer
Random.increment( step? )
Parameter step: Optional. Integer increment step size. The default value is 1. The starting value is 0.
Generates a global increment integer.
Global variables!!
Increment_increment () => 1 (0+1) // => 2 (1+1) Random. Increment (100) // => 102 (2+100) // => 103 (102+1)Copy the code
Mock.mock()
Mock.js intercepts Ajax requests by overwriting and emulating the behavior of native XMLHttpRequest
The current version only blocks Ajax requests, so I don’t write much about this method, but you can check the official documentation for those interested
Mock.mock( rurl? , rtype? , template|function( options ) )
- Mock.mock( template )
- Mock.mock( rurl, template )
- Mock.mock( rurl, function(options) )
- Mock.mock( rurl, rtype, template )
- Mock.mock( rurl, rtype, function(options) )
Parameter rURL: Optional. Indicates the URL to be intercepted. It can be a URL string or A URL re.
For example /\/domain\/list\. Json/and ‘/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.
Contains url, type, and body attributes. Refer to the XMLHttpRequest specification.
// Mock.mock( rurl, rtype, template )
Mock.mock(/\.json/, 'post', {
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL'
}]
})
$.ajax({
url: 'list.json',
type: 'post',
dataType: 'json'
}).done(function (data, status, jqXHR) {
console.log(data)
})
Copy the code
Mock.setup(settings )
Parameter Settings: Mandatory. Indicates the configuration item object. Configure the behavior when intercepting Ajax requests.
Mock. Setup (Settings) is only used to configure Ajax requests
Settings: indicates the configuration item
timeout
Optional. Specifies the response time, in milliseconds, for the intercepted Ajax request.
The value can be a positive integer, such as 400, indicating that the response will not be returned until 400 milliseconds later
It can also be ‘200-600′, indicating a response time between 200 and 600 milliseconds. The default value is ’10-100’.
Mock.setup({
timeout: 400
})
Mock.setup({
timeout: '200-600'
})
Copy the code