Please refer to the official documentation here

Please refer to the project source here

The Mock introduction

  • When front-end engineers need to develop in parallel independently of the back-end, the back-end interface is not complete, so how does the front-end get the data
  • At this point, consider the front end to build the Web Server itself to simulate fake data. Here, we use mockJS, a third-party library, to randomly generate data and intercept Ajax requests
  • Test pile, simulating the return of the object under test, used for testing
  • Mock refers to mock Server, which simulates interface data returned by the server and is used for front-end development and third-party interface tuning
  • Mockjs schematic:

The mock characteristics

  • Front end separation
  • Increase the authenticity of unit tests
  • Development invasive-free: AJAX requests can be intercepted and simulated response data returned without modifying existing code
  • Use simple
  • Rich data types: supports the generation of random text, numbers, booleans, dates, email addresses, links, pictures, and colors
  • Easy extension: support extension of more data types, support for custom functions and re

Create a MockJS file that prints the output of the test file

  • Create the testmock. js file and execute the output: node testmock. js
const Mock = require('mockjs'); Var data = Mock. Mock ({/ / the value of the attribute list is an array, containing 1 to 10 elements' list | 1-10 ': [{' id | + 1:1, / / id on the 1}]}); // console.log(json.stringify (data, null, 4)); Const obj = Mock. Mock ({id: '@id', // random number id username: '@cname', // random Chinese name date: '@ date (), / / randomly generated date avator:' @ image (\ '200 x200 \', \ 'red \', \ '# FFF \', \ 'avator \') ', the description: '@ the description ()', IP: '@ip()', email: '@email()', }); // console.log(obj); / / create an array object const jsonObj. = the Mock Mock ({' array | 20 ': [{' id | + 1:1, / / id on the username:' @ cname, / / a randomly generated Chinese name date: '@date()', // random generated date}]}); console.log(jsonObj);Copy the code

Mockjs files are used in vue projects

1. Build vUE scaffolding

Reference here

2. Install the dependencies required by the project

NPM install axios --save creates random data using mockjs --save-dev. NPM install mockjs --save-dev creates random data using json5 --save-devCopy the code

3. Create the. Env. development file in the root directory of the project

MOCK=true
Copy the code

Create a new index.js file in the mock directory

const fs = require('fs'); const path = require('path'); const Mock = require('mockjs'); //mockjs import dependency module const JSON5 = require(' JSON5 '); Var json = fs.readfilesync (path.resolve(__dirname, filePath), 'utf-8'); Parse (json); // Parse and return json5. parse(json); Module.exports = function (app) {if (process.env.MOCK == 'true') {// Listen for HTTP request app.get('/user/userinfo', function (rep, // The getJsonFile method defines how to read a JSON file and parse it into a data object var json = getJsonFile('./data/ userinfo.json5 ');  // Pass json into the mock. Mock method and the generated data is returned to the browser res.json(mock.mock (json)); }); Get ('/user/userinfo2', function (rep, res) {var json = getJsonFile('./data/ objjson.json5 '); // Pass json into the mock. Mock method and the generated data is returned to the browser res.json(mock.mock (json)); }); }};Copy the code

5. Create the JSON5 data source file

Userinfo.json5 file {id: '@id', // id id username: '@cname', // generate Chinese name date: '@date()', // generate date avator: '@image(\'200x200\',\'red\',\'#fff\',\'avator\')', description: '@description()', ip: '@ip()', email: '@ email ()} objJSON. Json5 file {' array | 4' : [{' id | + 1:1, / / id on the username: '@ cname, / / a randomly generated Chinese name date: '@date()', // random generated date}]}Copy the code

6. Create the vue.config.js configuration file

Module.exports = {devServer: {// provides the ability to execute custom middleware inside the server before all other middleware before: require('./mock/index.js')// introduce mock/index.js}};Copy the code

7. Send AJAX requests

<template> <div class="hello"> <h1> hahaha </h1> </div> </template> <script> import axios from 'axios'; export default { name: 'HelloWorld', mounted() { axios.get('/user/userinfo2').then(res => { console.table(res.data); }).catch(err => { console.error(err); }); }}; </script> <style scoped> </style>Copy the code