Image from Internet

Common solutions to front-end mocks

Debugging Mock data is an essential step in front-end construction. There are four common front-end Mock schemes:

  1. Hard coding at the code level is like having a function that requests the return data from an interface, gets the return data, and does something with that return data. You can then hardcode a data variable directly into your code that holds the returned Mock data. This Mock method is relatively simple to use, but it has the obvious disadvantage of changing the code logic and being too coupled to the code. And can not simulate the real network request process, strong limitations, narrow coverage.

  2. A typical solution to intercepting in front-end JS is mock.js, which makes it painless to intercept Ajax requests by mounting the JS file before the business code. This Mock approach, while partially decoupled from the code compared to hard coding, is not completely decoupled from the business code (because you must mount a JS and Mock configuration). Although a number of Mock apis are provided, there is still no way to make real network requests and the simulation is not realistic enough. This approach also has some drawbacks, as it is an adaptation of XHR objects, which is not compatible in some cases, such as with older browsers such as IE8, and the newer Fetch API.

  3. Fiddler and Charles can Mock a network request by intercepting it and replacing it with Mock data. The main advantage of this method is its high authenticity. However, the operation procedure of this method is tedious, and it is not convenient for unified configuration and the Mock cost is high.

  4. The best solution for mock-Server is nothing more than building a separate mock-server that all interfaces point to in the early stages of development. Because of the potential for cross-domain situations, it is common to have a set of interface agents in your development environment. This scheme is not invasive to the business code at all and has strong versatility. The disadvantages are also obvious, with high cost (and the need to set up and manage another mock-Server service).

Interface defines the schema that is combined with Mock data

The most common solutions are the ones mentioned above, or tweaks based on them, but the general idea is the same. The essence of a Mock is to allow the interface consumer to develop independently of the interface producer. However, this separation does not mean that the interface definition is developed independently of the producer’s interface definition. Consistency between the interface definition and Mock data is also an issue that we must consider to ensure that the Mock data conforms to the requirements in the interface definition. So there’s actually one more question to consider: how do you combine maintenance of interface definitions with mocks?

Fortunately, we have RAP. RAP is a great tool. It is a visual interface management tool that manages all of the interface development definitions in their required format and generates Mock data from those definitions to present to consumers.

Now that RAP provides us with Mock-Server services, the next thing we’re missing is how to make the web requests in our code directly accessible to RAP. RAP offers a plug-in JS that extends mock. JS to intercept requests on a page, but for now only supports Kissy and jQuery. To this end, we developed a set of tools based on Koa and the Rap-Node-plugin provided by RAP, which can forward all requests intercepted in the configuration to RAP and return the data generated by RAP to the requestor. In addition, due to the limited Mock rules of RAP and the frequent changes in the interface definition document, we have also added a local Mock solution that can change the local local-mock.js file anytime and anywhere to avoid frequent editing of RAP documents. Native Mocks also support dynamic return of mock data in the form of functions, greatly improving mock data generation capabilities. In addition, network latency is sometimes necessary in network request mocks, so we can determine how long it takes for the interface to return by adding a _delay field to the interface definition, and other underscore fields can be added as needed. Configuration in RAP:





RAP Interface Configuration

Mock scheme implementation

The solution is mainly composed of the following four components:





The mock tools

  • Config.js contains some configuration for mock tools

    /** * Default configuration */
    export default {
    PATH: '/pc/*'.// Path to intercept by default
    USE_RAP: true.// Defaults to true and will find and call the interface on RAP
    RAP_CONFIG: {
      host: 'rap.fe.yeshj.com'.// Start the service host
      port: 80./ / the port number
      projectId: 115.// project ID of RAP configuration
      mock: '/mockjsdata/'./ / RAP prefix
      wrapper: ' ' // No packaging required}}Copy the code
  • Filter. js KOA middleware intercepts the request PATH configured in config and obtains the request return data according to the relevant configuration. The return data is wrapped to a certain extent and returns as Mock data. The _delay operation associated with the interface is also implemented in this middleware

  • Local_mock. js is responsible for storing local mock rules and data. The _delay keyword is set here. Header supports user-defined return headers, and body data can be generated in the form of functions.

    module.exports = {
    "POST /pc/check": {
      "_delay": 1000."header": {
        "Content-Type": "application/json; charset=utf-8"
      },
      "body": function (ctx) {
        return {
          "status": 0."data": {
            "ctx": ctx
          }
        }
      }
    },
    "POST /pc/info": {
      "_delay": 0."header": {
        "Content-Type": "application/json; charset=utf-8"
      },
      "body": {
        "data": {
          "id": "12121212"
        },
        "message": "Success"."status": 0}}}Copy the code
  • Rap_connector.js This component encapsulates rap-node-plugin for easy invocation.

Development environment integration

Here’s how to integrate mocks into our development environment.

  • The mock scheme is not suitable to be wrapped as a separate node_module because it involves configuration tweaking and rewriting of local mock data. Therefore, we choose to integrate the mock scheme into the build tool of the project. The directory level is as follows:




Paste_Image.png

  • Add a new script mock to package.json:

    "scripts": {
      "start": "npm run mock"."mock": "babel-node ./tools/build/server.js --dev --mock"
    }Copy the code
  • Injecting mock middleware into KOA:

    if (argv.mock && config.mockEnable) {
      let mockFilter = require('.. /mock/filter.js');
      app.use(mockFilter());
    }Copy the code

The last step is as simple as doing some simple configuration in mock/config.js and typing NPM start into bash to enjoy our entire mock solution.


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