Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Debugging

API Mock

API Automated Testing

Sign up for free

Mock.js Usage Example

Start for free
Contents
Home / Basic Knowledge / Mock.js Usage Example

Mock.js Usage Example

Mock.js is a common JavaScript library for generating random data and intercepting Ajax requests. In this article, we will introduce the usage of Mock.js.

Mock.js is a common JavaScript library for generating random data and intercepting Ajax requests.

In this article, we will introduce the usage of Mock.js.

Installation

npm install mockjs --save

Basic Usage

Generate random user information.

name is a random English name. 2.

age is a random number from 15 to 25. 3.

  1. city is a random city.
const Mock = require('mockjs')
const user = {
  'name': Mock.Random.cname(),
  'age': Mock.Random.integer(15, 25),
  'city': Mock.Random.county(true)
}
// output results
console.log(JSON.stringify(user, null, 4))

Possible output results:

{
"name": "John Smith",
"age": 15,
"city": "East Fallowfield Township, Pennsylvania"
}

Generate a random array of user information. The length of the array is a random number from 1 to 10.

const Mock = require('mockjs')
const list = Mock.mock({
// The value of the property "list" is an array containing 1 to 10 elements
'list|1-10': [{
'id|+1': 1, // id starts from 1 and increments by 1
'name': '@cname', // Chinese name
'age|15-25': 1, // age between 15 and 25
'city': '@county(true)' // a random county name in China
}]
})
// Output the result
console.log(JSON.stringify(list, null, 4))

Possible output results:

{
"list": [
{
"id": 1,
"name": "Susan Smith",
"age": 20,
"city": "New York City, New York"
},
{
"id": 2,
"name": "Emily Johnson",
"age": 24,
"city": "Los Angeles, California"
},
{
"id": 3,
"name": "Andrew Davis",
"age": 25,
"city": "Chicago, Illinois"
}
]
}

Let's introduce the Mock.js API in detail.

Mock Data

Generate Random Data

Mock.Random.boolean()

Generate a random boolean. For example:

Mock.Random.boolean()

The return value is true or false.

Mock.Random.integer(min, max)

Generate a random integer with a specified range. For example:

Mock.Random.integer(0, 10)

Returns an integer between 0 and 10.

Mock.Random.float(min, max, dmin, dmax)

Generate a random floating-point number with a specified range and precision. For example:

Mock.Random.float(0, 100, 2, 5)

Return a floating-point number between 0.00 and 100.00000 with precision between 2 and 5 decimal places.

Mock.Random.string(length)

Generate a random string with a specified length. For example:

Mock.Random.string(10)

Return a random string with a length of 10 characters.

Mock.Random.name(middle?)

Generate a random name. For example:

Random.name()
// => "Larry Wilson"
Random.name(true)
// => "Helen Carol Martinez"

Mock.Random.date()

Generate a random date. For example:

Mock.Random.date()

Return a string representation of a random date. For example:1977-07-03.

Mock.Random.time()

Generate a random time. For example:

Mock.Random.time()

Return a string representation of a random time. For example 05:38:02.

Mock.Random.datetime()

Generate a random datatime. For example:

Mock.Random.datetime()

Return a string representation of a random datatime. For example2007-06-29T22:03:06.140Z.

Mock.Random.image(size, background, foreground, format, text)

Generate a random image with a specified size, background color, foreground color, format, and text. For example:

Mock.Random.image('200x100', '#50B347', '#FFF', 'png', 'Hello, Mock.js!')

The return value is a Base64 encoded string of the image.

Generate Data Specified by the Schema.

Mock.mock(template)

Generate simulated data based on data templates. The schema can generate complex data structures.

The syntax for the schema is as follows:

  • Separate property names and property values with a colon :.
  • Separate properties with a comma,.
  • Property values can be strings and can contain placeholders represented by the @ symbol.
  • Property values can also be objects and can include generation rules represented by the syntax name|rule.

Example:

const Mock = require('mockjs')

const data = Mock.mock({
  'list|1-10': [{
    'id|+1': 1, // Starting from 1, increase by 1 each time
    'name': '@cname', // Random Chinese name
    'age|18-60': 1, // Integer between 18 and 60
    'gender|1': ['male', 'female'], // male or female
    'email': '@email' // Random email address
  }]
})

console.log(data)

Export:

{
"list": [
{
"id": 1,
"name": "Taylor Swift",
"age": 32,
"gender": "Female",
"email": "kbsc@pmpuaaq.pk"
},
{
"id": 2,
"name": "Jay Chou",
"age": 55,
"gender": "Male",
"email": "whq@zjfwq.uz"
},
...
]
}

Mock Interface

Mock.mock(url, template) Mock API requests based on the interface address and data template.

  • Mock.mock(method, url, template) Mock requests based on the request method, endpoint address, and data template.
  • Mock.setup({timeout: 400})  is used to specify the response time of the intercepted Ajax request. Setting it to 400 means that the response content will only be returned after 400 milliseconds. It can also be a string in the dash'-'style, such as '200-600', which means the response time is between 200 and 600 milliseconds.

The above is commonly used syntax in Mock, for more syntax please refer to the official documentation. Want to become a Mock master? Apidog is a powerful API documentation management tool that makes Mocking easier. Apidog syntax is fully compatible with Mock and extends some syntax that Mock doesn't have. Give it a try.