简介:
Mock.js 是一款模拟数据生成器,旨在帮助前端攻城师独立于后端进行开发,帮助编写单元测试。提供了以下模拟功能
- 根据数据模板生成模拟数据
- 模拟 Ajax 请求,生成并返回模拟数据
- 基于 HTML 模板生成模拟数据
例子:
mock.js
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html"> 5 </head> 6 <body> 7 <script src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script> 8 <script src="http://mockjs.com/dist/mock.js"></script> 9 <script> 10 Mock.mock(/\.json/, 'get', function(options) { 11 var url = options.url; 12 var data = url.substring(url.indexOf('?')+1); 13 return data; 14 }); 15 16 17 Mock.mock(/\.json/, 'post', function(options) { 18 return options.data; 19 }); 20 21 22 $.ajax({ 23 url: 'mock.json', 24 dataType: 'json', 25 type: 'get', 26 data: { 27 test: 'test' 28 } 29 }) 30 .done(function (data, status, jqXHR) { 31 $('<pre>').text(data) 32 .appendTo('body'); 33 }); 34 </script> 35 </body> 36 </html>
apitizer.js
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html"> 5 </head> 6 <body> 7 <script src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script> 8 <script src="./apitizer-master/apitizer.min.js"></script> 9 <script> 10 var schema = { 11 type : "object", 12 properties : { 13 id : { 14 type : "integer" 15 }, 16 username : { 17 type : "string" 18 }, 19 password : { 20 type : "string" 21 } 22 } 23 }, userStore; 24 25 apitizer.addSchema('user', schema); 26 userStore = apitizer.schemaStore('user', 0, { 27 id : apitizer.types.autoincrement() 28 }) 29 30 userStore.add({ 31 username : 'retro', 32 password : { 33 a: 'a', 34 b: 'b' 35 } 36 }); 37 38 apitizer.fixture('POST /login', function(params){ 39 var users = userStore.db(params) // Search the data in the store's database 40 if(users.count() === 0){ 41 throw {errors: ['Wrong credentials'], status: 401} 42 } else { 43 return users.first(); 44 } 45 }); 46 47 $.post('/login', { 48 username : 'asf', 49 password : 1338 50 }).then(function(data){ 51 $('<pre>').text(JSON.stringify(data, null, 4)) 52 .appendTo('body'); 53 }, function(error){ 54 55 }); 56 57 58 </script> 59 </body> 60 </html>