Mock.js is a tool that intercepts Ajax
requests and generates random data responses in front-end development. Can be used to simulate a server response. The advantage is very simple and convenient, non-intrusive, basic coverage of commonly used interface data types.
In our production practice, the backend interface is often late to come out, and also to write the interface document, so our front-end of many development will wait until the interface to us, so for our front-end is very passive, so there is no way to create false data to simulate the backend interface, the answer is yes. Someone should write a JSON file to simulate the background data, but very limited, such as add and delete to find out how to implement the interface, so today we introduce a very powerful plug-in mock.js, can be very convenient to simulate the back-end of the data, you can easily implement additions and deletions to change these operations.
Probably record the use of the process, detailed use can see mock document mock Wiki
Installation
Install with NPM: npm install mockjs
;
or direct <script src="http://mockjs.com/dist/mock.js"></script>
;
Data template format:
‘name|rule‘: value属性名|生成规则: 属性值
GET request
To initiate a GET request:
$.ajax({ url: ‘http://test.com‘, type: ‘get‘, dataType: ‘json‘}).done(function(data, status, xhr) { console.log(JSON.stringify(data, null, 4));});
Mock.js Response:
var obj = {' AA ':' 11 ',' BB ':' 22 ',' CC ':' 33 ',' DD ':' 44 '};Mock Response template Mock.mock (' Http://test.com ', {"User|1-3": [{Randomly generate 1 to 3 elements of an array' Name ':' @cname ',Chinese name' Id|+1 ':88,Attribute value is automatically added 1, initial value is 88' Age|18-28 ':0,18 to 28 is a random integer, and 0 is used to determine the type' Birthday ':' @date ("yyyy-mm-dd") ',Date' City ':' @city (True) ',Cities in China' Color ':' @color ',16 Binary Color' Ismale|1 ':TrueBoolean value' Isfat|1-2 ':true, //true probability is 1/3 ' fromObj|2 ': obj, //randomly gets 2 properties from obj object ' fromobj2|1-3 ': obj, //randomly gets 1 to 3 properties from the Obj object ' brother|1 ': [ ' Jack ', //randomly select 1 elements ' sister|+1 ': [ ' Jack ', ' Jim ', ' Lily ', //Array in order to select elements as results ' friends|2 ': [ ' Jack ', ' Jim '] //repeat 2 times attribute values generate a new array},{ ' GF ': ' @cname '}]})
You can see the results:
{"User": [{"Name":"Dong Jing","id":88,"Age":25,"Birthday":"2015-04-01","City":"Huaihua, Hunan Province","Color":"#c0f279","Ismale":false, "Isfat": false, "$", "AA" : "FromObj2": { "BB": ", "CC": ""}, " sister ": " Jack ", Span class= "hljs-attr" > "friends": [ "Jack", "Jim", "Jim"]}, { "GF": "Jeff Tian"}]}
Responses can also be used function
, such as:
Mock.mock(‘http://test.com‘, ‘get‘, function() { return Mock.mock({ "user|1-3": [{ ‘name‘: ‘@cname‘, ‘id‘: 88 } ] });});
Results:
{ "user": [ { "name": "许超", "id": 88 } ]}
POST request
To initiate a POST request:
$.ajax({ url: ‘http://test.com‘, type: ‘post‘, dataType: ‘json‘, data: { account: 888, pwd: ‘abc123‘ }}).done(function(data, status, xhr) { console.log(JSON.stringify(data, null, 4));});
Mock.js Response:
Mock.mock(‘http://test.com‘, function(options) { console.log(options); return Mock.mock({ "user|1-3": [{ ‘name‘: ‘@cname‘, ‘id|+1‘: 88 } ] });});
You can see the results:
"http://test.com", type: "POST", body: "account=888&pwd=abc123"}{ "user": [ { "name": "曾明", "id": 88 } ]}
Custom Response Time
You can customize the response time, either absolute or interval.
// 设置4秒后再响应Mock.setup({ timeout: 4000 }); // 设置1秒至4秒间响应Mock.setup({ timeout: ‘1000-4000‘ });
Data set
Mock.Random
is a tool class for generating random data in various formats. There are two ways to do this:
The first type:
// 生成一个email格式的字符串console.log(Mock.mock(‘@email‘)); // 结果: [email protected]
The second type:
var Random = Mock.Random;console.log(Random.email()); // 结果: [email protected]
The available types are:
Type |
Method |
Basic |
Boolean, natural, Integer, float, character, string, range, date, time, DateTime, now |
Image |
Image, Dataimage |
Color |
Color |
Text |
Paragraph, sentence, Word, title, Cparagraph, Csentence, Cword, Ctitle |
Name |
First, last, name, Cfirst, Clast, CNAME |
Web |
URL, domain, email, IP, TLD |
Address |
Area, Region |
Helper |
Capitalize, upper, lower, pick, shuffle |
Miscellaneous |
GUID, ID |
If you don't have the kind you need, you can also customize the extension as follows:
Random.extend ({WeekdayfunctionDate) {var weekdays = [' Sunday ',' Monday ',' Tuesday ',' Wednesday ',' Thursday ',' Friday ',' Saturday '];ReturnThis.pick (weekdays); },Sex: function (date) { var sexes = [' Male ', ' female ', ' neutral ', ' unknown ']; return This.pick (sexes);}}); Console.log (Random.weekday ()); //Result: Saturdayconsole.log (Mock.mock (' @weekday ')); //Result: 112TuesdayConsole.log (Random.sex ()); //Result: Male console.log (mock.mock (' @sex ')); //Result: Unknown
Check
Mock.valid(template, data)
: Used to verify that real data data
template
matches the data template
var tempObj = { "user|1-3": [{ ‘name‘: ‘@cname‘, ‘id|18-28‘: 88 } ]};var realData = { "user": [{ ‘name‘: ‘张三‘, ‘id‘: 90 } ]};console.log(Mock.valid(tempObj, realData));
JSON Schema
Mock.toJSONSchema(template)
: Used to Mock.js
transform the style data template template
intoJSON Schema
var tempObj = { "user|1-3": [{ ‘name‘: ‘@cname‘, ‘id|18-28‘: 88 } ]};console.log(Mock.toJSONSchema(tempObj));
增删改查这些操作
1. A simple example:
Mock.mock (' http://123.com ', { ' name|3 ': ' Fei ',//This defines the data as a template form below will introduce ' age|20-30 ': +,}) $.ajax ({ URL: ' http ://123.com ', dataType: ' json ', success:function (e) { console.log (e) }})
In this example, we intercept that the data returned by the address http://123.com is an object with name and age, then the data returned by Ajax is the data of the mock definition, and the returned data is in the following format:
{ name: ' Feifeifei ', age:26,}
As for the format of the above definition template data, we will introduce the following.
2. Describe how to define data
Each property in the data template consists of 3 parts: The property name, the build rule, the property value:
Property name NameGenerate Rules RuleProperty values Value' Name|rule‘: Value
1. ' Name|min-max ': string by repeatingstring
Generates a string that repeats more than or equalsmin
, less than or equal tomax
Example: ' lastname|2-5 ': ' Jiang ', repeat jiang this string 2-5 times
2. ' Name|count ': string by repeatingstring
Generates a string that repeats the number of times equal tocount
Example: ' firstname|3 ': ' Fei ', repeat FEI this string 3 times, print out is ' Feifeifei '.
3. ' Name|min-max ': number generates a value greater than or equal tomin
, less than equalsmax
The integer, property valuenumber
Just used to determine the type.
Example: ' age|20-30 ': 25, generates an integer greater than or equal to 20, less than or equal to 30, and the property value 25 is used only to determine the type
4. ' Name|+1 ': The Number property value is automatically added 1, the initial value isnumber
Example: ' big|+1 ': 0, the attribute value is automatically added 1, the initial value is 0, after each request on the previous basis +1
5. ' Name|min-max.dmin-dmax ': number generates a floating-point, integer part greater than or equal tomin
, less than equalsmax
, the fractional part is reserveddmin
Todmax
-bit
Example: ' weight|100-120.2-5 ': 110.24, generating a floating-point number, integer part greater than or equal to 100, less than or equal to 120, fractional portion reserved 2 to 5 bits
6. ' Name|1 ': Boolean randomly generates a Boolean, the probability of a value of true is 1/2, the probability of a value of false is also 1/2
Example: ' Likemovie|1 ': boolean, randomly generating a Boolean, the probability of a value of true is 1/2, and the probability of a value of false is also 1/2.
7. Attribute values are objects:var obj={' host ': ' Www.baidu ', ' Port ': ' 12345 ', ' node ': ' Selector '}
7-1. ' Name|count ': Object object
randomly selects a property from the property value count
.
Example: ' life1|2 ': obj,From the propertiesValueRandomly select 2 properties in obj
7-2. ' Name|min-max ': ObjectFrom the property valueobject
Random Selection inmin
Tomax
A property
Example: ' life1|1-2 ': obj, randomly picking 1 to 2 properties from the attribute value obj.
8. The attribute value is an array: var arr=[' Momo ', ' Yanzi ', ' Ziwei ']
8-1. ' name|1 ': array array
randomly selects 1 elements from the attribute value as the final value
Example: ' friend1|1 ': arr, randomly selects 1 elements from the array arr as the final value.
8-2. ' name|+1 ': array array
selects 1 elements in the order of the attribute values as the final value.
Example: ' friend2|+1 ': arr, which selects 1 elements sequentially from the attribute value arr, as the final value, the first time is ' Momo ', the second request is ' Yanzi '
8-3. ' Name|count ': Array array
generates a new array with repeating attribute values, repeating the number of times count
.
Example: ' friend3|2 ': arr, repeat arr this number 2 times as this attribute value, get data should be [' Momo ', ' Yanzi ', ' Ziwei ', ' Momo ', ' Yanzi ', ' Ziwei ']
8-4. ' Name|min-max ': Array array
generates a new array by repeating attribute values, repetition times greater than min
or equal, max
例子:‘friend3|2-3‘:arr,//通过重复属性值 arr 生成一个新数组,重复次数大于等于 2,小于等于 3
3.实际的ajax请求例子:
less than or equal to
var arr=[' Momo ', ' Yanzi ', ' Ziwei '] var obj={' host ': ' Www.baidu ', ' Port ': ' 12345 ', ' No De ': ' selector '} mock.mock (' http://www.bai.com ', {' firstname|3 ': ' Fei ',//Repeat FEI this string 3 times, print out is ' Fei Feifei '. ' lastname|2-5 ': ' Jiang ',//Repeat Jiang this string 2-5 times. ' big|+1 ': 0,//attribute value is automatically added 1, initial value is 0 ' age|20-30 ': 25,//generates an integer greater than or equal to 20, less than or equal to 30, the property value 25 is used only to determine the type ' weight|100-1 20.2-5 ': 110.24,//generates a floating-point number, the integer part is greater than or equal to 100, less than or equal to 120, and the fractional portion retains 2 to 5 bits. ' likemovie|1 ': boolean,//randomly generates a Boolean, the probability of a value of true is 1/2, and the probability of a value of false is also 1/2. ' friend1|1 ': arr,//randomly selects 1 elements from the array arr as the final value. ' friend2|+1 ': arr,//selects 1 elements from the attribute value arr, as the final value ' friend3|2-3 ': arr,//generates a new array with duplicate attribute values, with a repeat count of greater than or equal to 2, less than or equal to 3. ' life1|2 ': obj,//randomly selects 2 properties ' Life1|1-2 ' from the attribute value obj: obj,//randomly selects 1 to 2 properties from the attribute value obj. ' REGEXP1 ':/^[a-z][a-z][0-9]$/,//generated string with regular expression}) $.ajax ({url: ' Http://www.bai. com ', DataType: ' JSON ', Success:function (e) {Console.log (e)}})
4. How to achieve data deletion and modification of the analog data interface
Below I will simulate the interface implementation of back-end Delete function
/* Simulate how to delete data */var arr=[ {name: ' Fei ', age:20,id:1}, {name: ' Liang ', age:30,id:2}, {name: ' June ', Age:40,id : 3}, {name: ' Ming ', Age:50,id:4}]mock.mock (' http://www.bai.com ', ' delete ', function (options) { var id = parseint (options.body.split ("=") [1])//get deleted ID var index; for (var i in arr) { if (arr[i].id===id) {///= in the array arr find this ID index=i break ;} } Arr.splice (index,1)//the object corresponding to the ID from the array to remove the return arr;//return this array, that is, to return the processed false data}) $.ajax ({ URL: '/http Www.bai.com ', type: "Delete", data:{ id:1//assumes the need to delete the id=1 data }, dataType: ' JSON ', Success:function (e) { console.log (e) }})
As for more detailed documents can go to the official website to view, Http://mockjs.com/,Mock.js easy to learn, can facilitate the rapid development of the front-end, you can also define the required format, so that the backend with you, in accordance with your format to write his back-end code.
Reference: https://www.cnblogs.com/zhenfei-jiang/p/7235339.html
1190000008839142
Blocking Ajax in Mock.js development