Mockjs

Mock data is familiar to anyone who has used it, and its benefits are endless. For example, the following is a good description of MockJS:

  1. Front end separation
  2. You can intercept Ajax requests and return simulated response data without modifying the existing code.
  3. Data type richness
  4. Simulate various scenarios with random data. (etc.)

Summarize up to until the backend interface is developed, the front can use existing interface documentation, intercept ajax on the request of the real, and according to the rules of mockjs mock data, simulate the real interface the data returned, and will return to participate in the corresponding data random simulation data interactive processing, so really realized the separation of Taiwan before and after the development.

Examples are Easy Mock, RAP2, and so on. Next, let’s mock

Installation and use

Here I build the project based on vUE and use mocks. First, of course, I install mocks using our NPM

npm install mockjs 
Copy the code

To make the directory structure clearer, we can create a separate folder for Mock to hold mockJS mock data for easy reading. You then need to import this file in the main entry function (main.js).Mock. Mock (URL, type, data)You need to import the mock module and cache it before defining it:

const Mock = require('mockjs')
Copy the code

Now you can start to define the data. The mock provides placeholder methods as follows:

Type 1: name | rules: content

Mock.mock('/test', { 'data|1-4': "Dumb"}) randomly generated1to4A 'mute'Copy the code

Type 2: Mock comes with a template

Mock.mock('/province'.'@province') randomly generates a domestic provinceCopy the code

Type 3: Define data according to convention rules

// Get the mock.Random object
const Random = Mock.Random
// Set delay (optional)
Mock.setup({
  timeout: 1000
})
Mock.mock('/api',
  {
    data: {
      msg: 'success'.code: 0.data: {
        Mock placeholders refer to methods through placeholders
        / / random IP
        'ip': '@ip'./ / random url
        'url': '@url'.//1: randomly select one of them
        "job|1": ["web"."UI"."python"."php"].//+1: the first request is the first one by default
        "routerName|+1": ['home'.'about'.'testTable'.'mockImg'.'calculate'.'keyboard'.'canvas'].// The calling method is written like @email
        email: Random.email(),
      }
    }
  })
Copy the code

Matters needing attention

Without further ado, get right to the code

download() {
  // When the URL is empty, the Ajax request is sent to the current page
  this.downloadFileByURL();
},

downloadFileByURL(url, fileName = "download") {
  this.getBlob(url).then(blob= > {
    const a = document.createElement("a");
    console.log(blob);
    // Mock intercepts native Ajax requests and turns XMLHttpRequest into MockXMLHttpRequest
    // An error page or garble is returned (if file stream)
    ↓↓↓ createObjectURL() needs to accept an object argument
    a.href = window.URL.createObjectURL(blob);
    a.download = `${fileName}`;
    a.click();
  });
  return false;
},

getBlob(url) {
  return new Promise(resolve= > {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () = > {
      if (xhr.status === 200) {
        console.log(xhr,'---xhr') resolve(xhr.response); }}; xhr.send(); }); }Copy the code

The above encapsulates a method for downloading files through native Ajax requests and the a tag features. The thing to notice herewindow.URL.createObjectURL(blob)The argument to this method is that it receives an object like thisThe mock data intercepts a step in the Ajax request, that is, when a new XML object is created, it is changed to a mockXML object, as shown below

Before masking the mock:

After masking the mock:Note that when I call this step, I don’t pass in the URL, it will request the current page by default.

this.downloadFileByURL();
Copy the code

So before masking the mock, returnresponseThe HTML of his current page does not return a BLOb object, causingwindow.URL.createObjectURL(blob)Is an error in this step, if it is in the actual request interface returns the file, then he will file stream directly back to you, you see is a bunch of garbage characters printed (below), that is to say, no blocking by the ajax request to return before the mock blob data processing, he won’t do what he’s got give you what, it lead tocreateObjectURL(blob)Parameter transfer error.

conclusion

  1. All HTTP requests made by the front end are intercepted, whether or not Mock. Mock is turned on, and HTTP requests are intercepted, which is why the end cannot get HTTP requests without Mock. Therefore, once a mockJS reference is made, HTTP requests cannot be made through the front end and will be intercepted by MockJS.
  2. Mock data cannot be captured by a Network because it is not a real request.

Reference article:

  1. Official documentation: github.com/nuysoft/Moc…
  2. Example tests (you can print data mocks directly at the console) : mockjs.com/examples.ht…