1. 程式人生 > 程式設計 >使用Mock.js生成前端測試資料

使用Mock.js生成前端測試資料

Mock.js是一個模擬資料生成器,可以讓前端獨立於後端進行開發。如果你正在開發一個前端頁面,可是後臺還沒有完成供你呼叫的Api,並且資料格式已經確定,那麼你就可以使用Mock.js模擬相關的介面,生成假資料來檢視頁面效果。Mock.js的功能:生成隨機資料,攔截 Ajax 請求。

參考文件:https://github.com/nuysoft/Mock/wiki/Getting-Started

語法規範:https://github.com/nuysoft/Mock/wiki/Syntax-Specification

安裝

npm install mockjs

建立模擬Api,攔截Ajax請求,返回測試資料

  //模擬後臺
  Mock.mock('http://api.com',{
    "user|5-10": [{
      'name': '@cname',//中文名稱
      'age|1-100': 100,//100以內隨機整數
      'birthday': '@date("yyyy-MM-dd")',//日期
      'city': '@city(true)'  //中國城市
    }]
  });

傳送ajax請求

  //JQuery方式
  $.ajax({
    url: 'http://api.com',dataType: 'json'
  }).done(function(data,status,xhr) {
    console.log(
      JSON.stringify(data,null,4)
    )
  });
  //原生ajax方式
  function myajax(url) {
      if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        try {
          ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try {
            ajax = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
        }
      }
      if (!ajax) {
        window.alert("不能建立XMLHttpRequest物件例項.");
        return false;
      }
      ajax.open("GET",url,true);
      ajax.send(null);
      ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && ajax.status == 200) {
          console.log(ajax.responseText);
        }
      }
    }

  myajax('http://api.com');

檢視響應

{
  "user": [
    {
      "name": "鍾麗","age": 17,"birthday": "1983-11-01","city": "內蒙古自治區 赤峰市"
    },{
      "name": "陳豔","age": 25,"birthday": "1973-07-10","city": "河南省 駐馬店市"
    },{
      "name": "馮霞","age": 59,"birthday": "2010-10-28","city": "澳門特別行政區 離島"
    },{
      "name": "賈秀英","age": 63,"birthday": "1973-01-22","city": "新疆維吾爾自治區 伊犁哈薩克自治州"
    },{
      "name": "周勇","age": 34,"birthday": "1985-05-21","city": "湖南省 衡陽市"
    }
  ]
}

示例

// 使用 Mock
var Mock = require('mockjs')

/**
 * 
 * 資料模板
 * 屬性名|生成規則: 屬性值
 */
var data = Mock.mock({
  // 屬性 list 的值是一個數組,其中含有 1 到 10 個元素
  'list|1-10': [{
    // 屬性 id 是一個自增數,起始值為 1,每次增 1
    'id|+1': 1,'name': '@FIRST'
  }]
})

// 輸出結果
console.log(JSON.stringify(data,4))

執行結果

{
"list": [
{
"id": 1,
"name": "Larry"
},
{
"id": 2,
"name": "Edward"
},
{
"id": 3,
"name": "Jessica"
},
{
"id": 4,
"name": "William"
},
{
"id": 5,
"name": "Christopher"
},
{
"id": 6,
"name": "Michael"
},
{
"id": 7,
"name": "Susan"
},
{
"id": 8,
"name": "Shirley"
},
{
"id": 9,
"name": "Angela"
},
{
"id": 10,
"name": "George"
}
]
}

到此這篇關於使用Mock.js生成前端測試資料的文章就介紹到這了,更多相關Mock.js生成測試資料內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!