This article looks at mock tools, which are typically used for separate development at the front end, for simulating interface data at the front end when the interface is not provided, and for automated testing. The main content is a deeper look at several of the MockJS apis from the source code.

The rest of the front-end development toolset series is here


1 overview

Mockjs has two main features

  • Returns data based on the incoming template
  • Intercepts the Ajax request and returns the data corresponding to the template

The library is simple, with the entry file exposing a Mock object

Var Mock = {Handler: Handler,// used to generate Random numbers Util: Util,// used to generate Random numbers XHR: RE: RE,// toJSONSchema: ToJSONSchema,// convert the mock. js-style data template toJSONSchema valid: valid,// check whether the real data data matches the data template template heredoc: Util. Heredoc,// can be used to write multi-line templates setup: function(Settings) {return xhr.setup (Settings)},// Configure custom XHR objects _mocked: Mock :function(rurl, rtype, Template) {// mock.mock (template) // Is considered a template when there is only one argument if (arguments.length === 1) {return handler.gen (rurl)} // Mock. Mock (rurl, template) // With two arguments, (arguments.length === 2) {template = rtype rtype = undefined} // XHR if (XHR) window.XMLHttpRequest = XHR Mock._mocked[rurl + (rtype || '')] = { rurl: rurl, rtype: rtype, template: template } return Mock } }Copy the code

2 use

For this library we will focus on one API and one syntax

2.1 API

This API is Mock. Mock, as mentioned above, can pass one to three arguments

Mock.mock( rurl? , rtype? , template|function( options ) )Copy the code
  • Returns data that matches the specified template or executes the specified callback
  • When two, it intercepts ajax requests for the specified path and returns data with another parameter
  • When three adds a match to the request method on top of two

One of these arguments is actually called handler.gen (rURL), which is defined here. In this case, the template argument is parsed, and the template is parsed. In other cases, the path and method are matched before parsing, as described in the next section.

2.2 grammar

This syntax is the template parameter from the previous section, and is divided into data templates and data placeholders. Parsing of templates is handled in handlers.

2.2.1 Data Template

A data template consists of three parts

// Attribute name // generate rule rule, optional, Including min - Max, count, min, Max, min, Max, dcount, count. Dmin on3dmax, count. Dcount, + step / / the value attribute values' name | 'rule: the valueCopy the code

The specific meaning of the generation rule is further determined according to the type of the attribute value

function type(obj) {
    return (obj === null || obj === undefined) ? String(obj) : Object.prototype.toString.call(obj).match(/\[object (\w+)\]/)[1].toLowerCase()
}
Copy the code

Property values can contain placeholders described in the next section. Property values are used to specify the type and initial value of the return value

Depending on the type of the attribute value, the following situations occur

  • string
    • Min-max indicates the range of repetitions
    • Count Number of repetitions
  • number
    • +step When multiple groups are output at the same time, the last one is added step over the previous one
    Mock.mock({
    'list|1-10': [{
        'id|+1': 1,
    	}],
    }
    Copy the code
    • Min – Max range
    • Min-max. Dmin-dmax Indicates the range from min to Max. The decimal point is between dmin and dmax
    • count.dcount
  • boolean
    • Count indicates that the current attribute value is a probability multiple of the opposite attribute value. For example, 0 means that the current value has a probability of 0
    • The ratio of the current value of min-max to the probability of the opposite value
  • object
    • Count Selects count randomly from the attribute value
    • min-max
  • array
    • Count (1) selects an element in the array; otherwise, the number of times an element in the array is repeated
    • +step selects the first element in the array
    • Min-max Number of repeated attribute values
  • Function executes the return value of the object
  • Regexp reverse generates the matching string, this part of the source code here, interested can take a look

2.2.2 Data placeholders

A placeholder is a string starting with @ in the format of

@ placeholder @ placeholder (parameter [, parameter])Copy the code

Placeholders refer to methods in mock. Random and are equivalent to calling corresponding methods.

It can also be extended by random.extend, for example

Random.extend({ constellation: Function (date) {var constellations = [' Aries', 'Taurus',' Gemini ', 'cancer', 'Leo, virgo, libra, Scorpio, Sagittarius, Capricorn, Aquarius, 'Pisces '] return this.pick(constellations)}}) random.constellation () // => "Aquarius" Mock. Mock (' @constellation ') // => "Scorpio" Mock. Mock ({constellation: '@constellation'}) // => {constellation: "Sagittarius"}Copy the code

The source code is here, the documentation is here.


End and spend