1, the introduction
-
1.1, What do you see?
- Personal understanding of mocks and application scenarios.
- Instead of copying simple examples from the official website, teach you detailed MockJS deployment instructions by hand based on your actual work project. After reading it, you can use it directly in your own projects to meet the needs of normal work projects.
- This approach has advantages and disadvantages over implementing MockServer via Node’s dev-Server.
- Where this notation is applicable.
- Finally, my development environment is vue2+elementUI2+nginx.
-
1.2, What won’t you see?
- You won’t see a step-by-step explanation of mock syntax, which is explained in detail in the official documentation. If you still have a lot of doubts about how to use it, do it yourself in the project! In fact, this than you in Baidu and Google search for much faster, but also deeper impression!
- You will not see instructions for the relevant mock frameworks, such as JSON-server,easy-mock(which is quite handy!). And so on.
Mockjs functions and application scenarios
-
2.1, The function of mockjs
-
Production data: With mockJS, you can easily create lots of random text, numbers, booleans, dates, mailboxes, links, images, colors, etc.
-
Powerful interception capabilities: MockJS can do powerful Ajax interception. Can judge the request type, get the URL, request parameters and so on. You can then return mock mock data, or json files you’ve made up yourself. Powerful and easy to use.
-
-
2.2, Mockjs applies scenarios
- Front-end and back-end separation: Thanks to MockJS, front-end data requests are self-contained and “independent” of back-end development. In the early stage of the project, the front end can focus on its own front end presentation, and the back end can focus on its own back end interface and data processing. But the worst case of front end separation is that the front end plays its own game and the back end plays its own game. Wait until the joint investigation, found that the interface completely irrelevant! Therefore, during development, the front and back ends should also be in constant communication, timely confirmation of the latest interface and data structure. Swagger is recommended for management.
- Easy unit testing: Because MockJS produces a lot of random data, it simulates many request scenarios. So you can guarantee the authenticity of a single part of the test. But my personal feeling is still not a complete substitute for the real call back-end interface, back-end processing situation is more complex.
3. Mockjs project practice
-
3.1, install mockjs
npm install mockjs --save-dev
Copy the code
Check that MockJS is installed successfully by searching for the presence of MockJS in package.json and package-lock.json.
-
3.2. Create the mock folder structure
Description of each document:
Mock: Stores all mock related files in the root directory for easy access and viewing.
Test: Stores mock files grouped by project module. For example, device stores mock files required by the device module. Test is used to store the mock files needed for this demo.
Test-mock. js:mock main file. Mainly mock data, which is used to handle intercepting requests.
Test-json. json: stores false data in JSON format.
Index.js: file introduced later in main.js. The effect is to introduce mock.js for all modules.
Utils.js: Write in common simulation data methods according to project requirements. Convenient module to mock data.
-
3.3, Test-json. json description.
In the interface definition phase, the interface documentation provided by the back end contains the requested interface and the returned data instance. At this point, the interface is not accessible, but with MockJS, our front end can make Ajax requests. And in a JSON file. Copy and paste data instances from the interface document, and then modify them to achieve the most primitive and simplest data implementation. However, if the data has special requirements with a large number and complex structure, it is suggested to use the method given by MockJS to create the data.
-
3.4, Description of test-mock.js (key)
import Mock from 'mockjs' / / into the mock
import testJson from './test-json.json' // Import the JSON dummy data created above
import utils from '.. /utils' // Introduce common methods
const res =function (opt) {
//opt is the set of options for ajax requests. Contains url, Type, and body attributes
// opt.url indicates the requested URL.
//opt.type Specifies the request type, such as GET, POST, or delete
//opt.body is the requested parameter
//1, use mock methods to mock data
let mockData =Mock.mock({
'code':0.'msg':'success'.'list|1-10': [{'id|+1':1}}]);let data=JSON.stringify(mockData,null.4);// Convert the data
//2, determine the request parameters
let param=opt.body;// Save the request parameters with param
let result; // Use result to save the result of param validation
/ /... Omit the process of validating param
//3, return data according to the verification result
if(result===true) {// The result is correct
return data;
//return testJson can also return previously written JSON files. Choose according to the situation. If the data isn't complicated, I'm just going to return a.json file.
}else {
return {
// If the verification is incorrect, an error message is displayed
'msg':'Request parameter error'
}
}
}
Mock.mock(/devicemanage\/api\/pc\/dm\/device\/structure\/query\? token=/.'post',res)
// Use the function notation for mock(). This will get the parameters of the request, where the URL is written as the re.
//Mock.mock(rul,rtype,function(opt))
//rul: the url to intercept. There are two ways to write it, one is a string, for example, '/ API /device' means that only/API /device requests can be intercepted. However, we may often need to add additional parameters such as tokens to the URL.
// Then we need to write the second form, the regular expression/API \/device/, so that we can block all requests containing/API /device. This way we can write real urls directly when making Ajax requests.
//rtype: Indicates the type of Ajax request to intercept. For example, get, POST, PUT, and delete.
//function(opt): a function that responds to data, where opt is indicated at the top of the code.
Copy the code
-
3.5, Index. Js
import device from './device/device-mock'
import event from './event/event-mock'
import home from './home/home-mock'
import log from './log/log-mock'
import patrol from './patrol/patrol-mock'
import test from './test/test-mock'
Copy the code
It’s obvious from the code above that this file is just a collection of scattered mock files. Any new mock files you add later need to be introduced here.
-
3.6, Utils. Js
This js file is used to store common methods (such as JSON format conversion) and mock data (such as our device list and organization structure) that you need to use. I won’t post my own company code here. Mock your own common data against the official documentation and export it.
-
3.7, A description introduced in main.js
import mock from '.. /mock/index'
Copy the code
It’s also easy to introduce in main.js. Just import index.js as written above. At this point you have completed the mockJS project practice. Run and see!
4. Why didn’t I build the Mock Server with my own dev-server?
In short, it is not suitable for the project. The main reasons listed below are personal and in the context of the project. If you think you have other ideas or better suggestions or ideas, please feel free to comment.
- Using the MockJS project structure directly has fewer modifications and simpler syntax writing. Many tutorials on the web are made by making changes on dev-server. Then intercept using a proxyTable or before hook. However, I still feel that it is very complicated and the structure is not obvious, and I need to have a good understanding of the syntax and usage of Express, otherwise it is very easy to modify the error, and not very safe.
- When you modify MockJS, the page automatically refreshes to see your mock data. If you are making changes on dev-server, you need to run dev again. While you can install plug-ins instead of manually deving them, it’s not as efficient and convenient as automatically refreshing them.
- Mockjs has the highest priority in request interception: mockjs>nginx>dev-server. So you can use the mock.mock () method to block any request you want without worrying about Nginx or other proxies. When you use dev-server for interception, and you, like me, have nginx configured for your project, it’s a bit more of a hassle. You may also need to configure nginx to avoid intercepting dev-server requests. Then restart the service again and run dev again. Once the back-end interface is complete, you have to change back again.(for example: Nginx intercepts /devices, but this time it adds an interface path /devices/newApi that you need to intercept on dev-server. You will have to modify the configuration of nginx.
- Mockjs provides mock() methods that make it easier to restrict request types and get request parameters. And returns the corresponding data. You can also return.json files or mock data if you like.
- This file structure also allows modular management of mock files and is not complicated to implement. There is no need for modularity with Dev-Server.
Disadvantages of this method:
- Since MockJS is a JS layer, interception starts first. So sometimes you need to be careful not to conflict with the previously configured proxy.
- Because MockJS is completely front-end based, you need to manually modify it in a timely manner if the back-end interface changes.
5. Application scenarios
-
5.1 suitable for:
If you don’t have a lot of front-end developers, you have four or five people. And there is no trans-regional cooperation. In fact, this writing method can meet the current mock needs.
-
5.1 Not suitable for:
If there are many front-end developers, cross-regional cooperation, communication difficulties, and back-end interfaces need to be modified frequently. It doesn’t work that way! Easy-to-mock is recommended. Once deployed on the local Intranet, you can happily maintain mock data and interfaces with other front-end and back-end partners.