How to use the mock function from mockjs

Find comprehensive JavaScript mockjs.mock code examples handpicked from public code repositorys.

mockjs.mock is a function in the Mock.js library that generates mock data based on a defined schema.

106
107
108
109
110
111
112
113
114
115
    normal: counts[2],
    bad: counts[3]
  }
})

return Mock.mock({
  status: 200,
  message: 'OK',
  data: {
    base_param: baseParamData,
fork icon70
star icon196
watch icon8

48
49
50
51
52
53
54
55
56
57
  return json[keys[0]][keys[1]] || word
}

function handleMockWord(word) {
  if (!word || typeof word !== 'string' || word[0] !== '@') return word
  return Mock.mock(word)
}

/**
 *
fork icon41
star icon282
watch icon9

How does mockjs.mock work?

mockjs.mock is a function in the Mock.js library that generates mock data based on a defined schema. When you call mockjs.mock(schema), the function generates mock data based on the provided schema. The schema defines the structure of the mock data, including the types of data to generate and any constraints on the data. The schema is defined using a combination of data types and template strings that describe the data to be generated. For example, you can use the @string template to generate a random string, the @integer template to generate a random integer, and the @boolean template to generate a random boolean value. The mockjs.mock function generates data based on the schema by interpreting the templates and generating data of the appropriate type. The generated data is returned as an object that matches the structure of the schema. In essence, mockjs.mock provides a way to generate mock data based on a defined schema, making it easy to generate realistic data for testing and other purposes.

3
4
5
6
7
8
9
10
11
12
 */
let Mock = require('mockjs');
var Random = Mock.Random;
export function setString() {
    Random.word(3, 8);
    return Mock.mock('@word(3, 8)');
}

export function setBoolean() {
    Random.boolean();
fork icon20
star icon102
watch icon15

+ 5 other calls in file

0
1
2
3
4
5
6
7
8
9
const mockjs = require('mockjs')
const utils = require('../utils/index.js')

async function actives(ctx) {
  const { limit = 10, page = 1 } = ctx.request.query
  const data = mockjs.mock({
    [`data|${limit}`]: [
      {
        "id|+1": 1,
        "imgUrl|1": [
fork icon15
star icon51
watch icon1

+ 5 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const Mock = require("mockjs");

const data = Mock.mock({
  "users|3": [
    {
      "id|+1": 1,
      name: "@name",
      "age|18-30": 0,
      "gender|1": ["Male", "Female"],
      email: "@email",
    },
  ],
});

console.log(JSON.stringify(data, null, 2));

In this example, we first import the mockjs library. We then call Mock.mock(schema) to generate mock data based on the provided schema. The schema defines an array of 3 user objects, with each object containing properties like id, name, age, gender, and email. The @name and @email templates generate random names and email addresses. We then log the generated data to the console as a nicely formatted JSON string using JSON.stringify. When you run this code, it generates mock data that looks something like this: json Copy code

9
10
11
12
13
14
15
16
17
18
  return query
}

for (let i in mockData) {
  for (let key in mockData[i]) {
    Mock.mock(eval('/' + key.split(' ')[1].replace(/\//g, '\\\/') + '/'), key.split(' ')[0].toLowerCase(), function (options) {
      if (key.split(' ')[0].toLowerCase() == 'get') {
        options.query = options.url.split('?')[1]
          ? serialize(options.url.split('?')[1])
          : (options.body
fork icon29
star icon29
watch icon11

33
34
35
36
37
38
39
40
41
42
if (!fs.existsSync(filePath)) {
  callback(null,{});
}

try {
  var mock = Mock.mock(require(filePath));
  callback(null,mock);
} catch (e) {
  callback(e);
}
fork icon3
star icon6
watch icon6

73
74
75
76
77
78
79
80
81
82
    //var query = JSON.parse(stringJson);

    //query[key] = value;
    var query = {};
    query[key] = value;
    var data = Mock.mock(query);
    return data[getRealKey(key)];
}

var getRealKey = function(key){
fork icon2
star icon4
watch icon1

22
23
24
25
26
27
28
29
30
31
},
mac: function() {
    return Mock.mock(/[0-9A-F][02468ACE]:([0-9A-F]{2}:){4}[0-9A-F]{2}/);
},
listobject: function(obj) {
    let data = Mock.mock(obj);
    for (let key in obj) {
        return obj[key];
    }
}
fork icon1
star icon2
watch icon1

+ 3 other calls in file

14
15
16
17
18
19
20
21
22
23
module.exports = function (config) {
  var models = config.models || {};
  if (!_.isPlainObject(models)) {
    throw new Error(`Models must be an object. Found ${typeof obj}`);
  }
  var resource = Mock.mock(config.models || {});
  var adapter = new Memory('', { defaultValue: resource });
  if (config.save) {
    if (!fs.existsSync(dbPath)) {
      fs.writeFileSync(dbPath, JSON.stringify(resource));
fork icon0
star icon1
watch icon2

21
22
23
24
25
26
27
28
29
30
31
const http = require('http');


jsf.extend('mock', function () {
  return {
    mock: function (xx) {
      return Mock.mock(xx);
    }
  };
});

fork icon0
star icon0
watch icon1

+ 119 other calls in file

39
40
41
42
43
44
45
46
47
48
49
//   item = item.name;
//   jsf.format(item, () => {
//     if (item === 'mobile') {
//       return jsf.random.randexp('^[1][34578][0-9]{9}$');
//     }
//     return Mock.mock('@' + item);
//   });
// });


exports.schemaToJson = function (schema, options = {}) {
fork icon0
star icon0
watch icon1

+ 103 other calls in file

-3
fork icon0
star icon0
watch icon1

+ 4 other calls in file

14
15
16
17
18
19
20
21
22
23
24
    author: '@cname',
    'status|1': [0, 1]
  }]
})


const category = Mock.mock({
  'items|6': [{
    'id|+1': 1,
    title: '@ctitle',
    'status|1': [0, 1]
fork icon0
star icon0
watch icon1

+ 3 other calls in file

76
77
78
79
80
81
82
83
84
85
86
    value: '2',
    label: '人工智能202'
  }]
}


const academicList = Mock.mock({
  'items|30': [{
    'id|+1': 1,
    'stuId|1200000000-1200999999': 1200651257,
    name: '@cname',
fork icon0
star icon0
watch icon1