Using Mock. js to generate front end test data

  • 2021-10-15 09:29:49
  • OfStack

Mock. js is an analog data generator that allows the front end to be developed independently of the back end. If you are developing a front-end page, but the background has not completed Api for you to call, and the data format has been determined, then you can use Mock. js to simulate related interfaces and generate fake data to view the page effect. Function of Mock. js: Generate random data and intercept Ajax requests.

Reference document: https://github.com/nuysoft/Mock/wiki/Getting-Started

Syntax specification: https://github.com/nuysoft/Mock/wiki/Syntax-Specification

Installation


npm install mockjs

Create a simulated Api, intercept Ajax requests, and return test data


  // Analog background 
  Mock.mock('http://api.com', {
    "user|5-10": [{
      'name': '@cname',  // Chinese name 
      'age|1-100': 100,  //100 Internal random integer 
      'birthday': '@date("yyyy-MM-dd")', // Date 
      'city': '@city(true)'  // Chinese cities 
    }]
  });

Send an ajax request


  //JQuery Mode 
  $.ajax({
    url: 'http://api.com',
    dataType: 'json'
  }).done(function(data, status, xhr) {
    console.log(
      JSON.stringify(data, null, 4)
    )
  });
  // Native ajax Mode 
  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(" Cannot create XMLHttpRequest Object instance .");
        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');

View the response


{
  "user": [
    {
      "name": " Chung Li ",
      "age": 17,
      "birthday": "1983-11-01",
      "city": " Inner Mongolia Autonomous Region   Chifeng City "
    },
    {
      "name": " Chen Yan ",
      "age": 25,
      "birthday": "1973-07-10",
      "city": " Henan Province   Zhumadian City "
    },
    {
      "name": " Feng Xia ",
      "age": 59,
      "birthday": "2010-10-28",
      "city": " Macao Special Administrative Region   Outlying islands "
    },
    {
      "name": " Jia Xiuying ",
      "age": 63,
      "birthday": "1973-01-22",
      "city": " Xinjiang Uygur Autonomous Region   Yili Kazakh Autonomous Prefecture "
    },
    {
      "name": " Zhou Yong ",
      "age": 34,
      "birthday": "1985-05-21",
      "city": " Hunan Province   Hengyang City "
    }
  ]
}

Example


//  Use  Mock
var Mock = require('mockjs')

/**
 * 
 *  Data template 
 *  Attribute name | Generating rule :  Attribute value 
 */
var data = Mock.mock({
  //  Attribute  list  The value of is 1 An array containing  1  To  10  Elements 
  'list|1-10': [{
    //  Attribute  id  Yes 1 Self-increasing number, starting with  1 , each increase  1
    'id|+1': 1,
    'name': '@FIRST'
  }]
})

//  Output result 
console.log(JSON.stringify(data, null, 4))

Running result

{
"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"
}
]
}


Related articles: