One of the more difficult problems in parallel development (or parallel development between multiple businesses) is how to generate simulated data and simulate abnormal states. Until the discovery of mockJS, there was no good quick and easy way to generate simulated JSON data. Mockjs, however, requires the introduction of JS into the code, making it difficult to manipulate and, on the other hand, impossible to simulate an unusually convenient state. So a command line tool http-mock-json-server was developed to wrap a Node Server service to do some additional functionality.

For example, 🌰

Let’s see what it looks like in action

This mimics the effect of a REST-style news-list interface request, with type 1, 10 entries per page, page 2. As you can see in the figure, the id of the first item in data is 11.

Note that the extra redundant fields above were added for calculation purposes and are not business specific. Such as:

  • Index is the current sequence number used to calculate the value of the ID.
  • PageSize and pageIndex are placed in two separate places, and data is also used to calculate id. The outermost is used to calculate more and totalPageCount.

Let’s look at emulating a GET-style interface with the same functionality.

First you need an interface document, either one you send to the back end or one the back end sends to you.

Here is the interface to get the news list:

1 2 3
The name of the interface Get the news list
The request of the domain name api.example.com
Request the address /news/list
Request way GET
Request parameters
type The news type
pageSize How many pages per page
pageIndex Page number, starting at 1

Returns:

{
  "errorCode": 0.//0 indicates a normal return, and other values are error codes
  "message": "success".//
  "data":[{"id": 1.//News id
      "title": "The first is the Latin type".//News headlines
      "thumb": "".//News pictured above
      "type": "1".//News category 1 Technology, 2 Entertainment, 3 Sports
      "author": "Zhang SAN".//The author name
      "publish": "1472393346".//Release time
      "abstract": "The first type of text outside the table will be the most important. Do joint MAO subject to material but flat party horse market to group of pieces of technology must be asked." //Content abstract
    },
    .]."total": 83.//The total number of article
  "totalPageCount": 28.//Total number of pages
  "more": true //Is there a next page
}Copy the code

The first step is preparation

This step, it takes a little bit of time, but you only do it once.

  1. The Node environment is required to install http-mock-json-server.

    $ npm install -g http-mock-json-serverCopy the code

  2. Configure nginx to proxy all requests from api.example.com to local port 7071, and then restart nginx.

    server { listen 80; server_name api.example.com; charset utf-8; autoindex on; autoindex_exact_size on; index index.html; location ~ / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_set_header x-request-filename $request_filename; proxy_set_header Host $host; Proxy_pass http://127.0.0.1:7071; proxy_redirect off; }}Copy the code
  3. Get the IP address of api.example.com, which is assumed to be 192.168.8.218.

    $ping api.example.com ping api.example.com (192.168.8.218): 56 data bytes 64 bytes from 192.168.8.218: Icmp_seq =0 TTL =39 time=36.018 ms 64 bytes from 192.168.8.218: ICmp_seq =1 TTL =39 time=39.108 msCopy the code
  4. Configure hosts to point api.example.com locally, and then through the nginx proxy above to the mock data service.

    127.0.0.1 api.example.com
    Copy the code

Ok, all ready.

Step 3 Upgrade to REST style

  1. Interface documentation

    1 2 3
    The name of the interface Get the news list
    The request of the domain name api.example.com
    Request the address /news/list/{type}/{pageSize}/{pageIndex}
    Request way REST
    Request parameters
    type The news type
    pageSize How many pages per page
    pageIndex Page number, starting at 1
  2. Modify mock.json to change the pathName to REST style, leaving everything else unchanged.

  "pathname":"/news/list/{type}/{pageSize}/{pageIndex}"Copy the code

  1. Modify the template file list.mock, which will@GETReplace with@RESTEverything else remains the same.
{ "errorCode":0, "message":"success", "data|@REST['pageSize']":[{ "pageIndex":"@REST['pageIndex']", "pageSize":"@REST['pageSize']", "index|+1":1, "id": function(){ return (this.pageIndex - 1) * this.pageSize + this.index; }, "title": "@ctitle(3, 15)", "thumb": "@ image (' 200 x100)", "type" : "@ REST [' type ']", "author" : "@ cname", / / the author name "publish" : 14 \ d {8} / /, "abstract" : "@cparagraph(2)" }], "total": 83, "pageIndex":"@REST['pageIndex']", "pageSize":"@REST['pageSize']", "totalPageCount": function(){ return Math.ceil(this.total / this.pageSize); }, "more": function(){ return this.totalPageCount - this.pageIndex > 0; }}Copy the code
  1. Request, and you can see what the image looks like at the beginning of the article.

Note that modifications to mock.json and template files do not require the http-mock restart.

Step 4 Support jSONP and CORS across domains

Directly above:Api.example.com/news/list/1…

Jsoncallback and callback are supported as parameter names for JSONP.

Step 5 Abnormal state and delay

  1. Exception status, such as 502,500, can be modified by modifying the statusCode of the corresponding interface in the mock.json configuration file. Again, you don’t need to restart http-mock. After modification, you can refresh the page.
{
    "pathname":"/news/list/{type}/{pageSize}/{pageIndex}"."tpl":"list.mock"."statusCode": 502."delay": 0
  }Copy the code

The request returns error status code 502:

  1. The second exception is the return of incorrect data. If the type of the news list is incorrect and the errorCode is -1000, you need to modify the template file:

    {
      "errorCode": "- 1000."."message": "wrong type"
    }Copy the code

  2. Delay, change delay to 5000 ms, refresh the request.

{
  "pathname":"/news/list/{type}/{pageSize}/{pageIndex}"."tpl":"list.rest.mock"."statusCode": 200."delay": 5000
}Copy the code

You can see that the Wating time for this request is 5s:

In addition, the IP address and port of the proxy can also be changed dynamically, but the use scenario should be small.

The sixth step is abnormal scenario simulation

Because you modify mock.json or template files (for exceptions that occur in the returned data), you do not need to restart http-Mock. Therefore, it is very convenient to simulate the time variation of various abnormal scenarios.

  1. When obtaining data, check whether the loading effect takes effect. Modify the delay value of the corresponding interface, for example, 5000 seconds.

  2. When getting list data, you want to see the effect of a failed request on the second page after a successful request on the first page. You can modify statusCode or template files as required.

  3. Simulate a request failure, restore the error state (statusCode or template file), and then click the retrieve button to see if it works.

conclusion

Just as MockJS has solved the core problem of generating random data, http-mock-JSON-Server has added some ancillary features, complete with support for request parameter and exception state emulation, and of course incomplete. At least the days of hardcoding analog data should be over.

By bx 2016.12.23


Did this article help you? Welcome to join the front End learning Group wechat group: