preface
In the current project development with the separation of the front and back ends, in order not to affect the progress of the project, the development of the front and back ends is carried out simultaneously. In order not to affect the progress of our front-end development, it is usually the back-end students who first provide interface documents, and then the front-end students compare the interface documents to carry out data simulation to complete the work of front and back end docking. Mock data is used to simulate data. What are the methods for implementing mock data? … (⊙ _ ⊙;) … Let’s keep talking! (^ o ^ ●)
Mock data at the front end
There are many solutions to mock data at the front end, where I’ve gone back to old homesteads. ~ ▽ ~)┛ install force to run). The first and simplest is the dead data we wrote in the page (which should have been retrieved from the interface, but died in the page). The second is to mock data with mock.js; What other mocks are there in our project? Let’s talk about them
mock.js
Use mock.js package in your front-end project, then write mock data locally, generate a lot of mock code in the front-end code, and introduce unnecessary JS files.
Online Mock service
Fastmock has no data verification. Normal mock functions have fixed prefixes and customized URIs. There is no configuration for incoming parameters, only configuration for return values.
summary
- The mock. Js package is used in the front end project, which generates a lot of mock code and introduces unnecessary JS files.
- Online mock, front-end installation interface document, wait until the back-end interface development is completed, and then change the front-end interface request address to the back-end address for joint adjustment.
At my last company, functionality was about to be tested, and I encountered a strange problem, which led to my first time working in the office with a Java backend. The cause of the incident was as follows… Project originally yes PHP development, but for various reasons (you know), the back-end becomes, PHP + Java development model, this model, the company’s technical team for the first time to use, then there is the question of a strange flower, is a very important interfaces, front sends the request, passing out parameters, The back end says, “It’s not my problem. I’m interrupting. I did not receive the parameter. Check again if there’s something wrong with the front end.”
So I checked again, there is no problem, check the browser request, parameters are indeed delivered to the correct, and then is mutual bicker, after a variety of tests, analysis and detection, and finally solved the problem is the backend nginx proxy configuration problem.
Hand mock service
After experiencing the conflict with the backend, I was so angry that I invented a mock service at home for more than an hour, and then contributed it to the company and started to use it internally. There are mainly the following aspects, which gave me an idea to make my own mock service. Firstly, I am too stupid. Remember mockjs so many apis, mainly for my own use, not used to (ha ha) followed by some data and the data in the database with a company’s upstream and downstream link, and then according to the business of the company, has written the following local mock services, mainly to check whether the parameter is right, has the wrong circumstances. The most important reason for this is that the next time the backend fails to receive an argument, the backend will respond with “I can receive arguments from Node, but Java can’t.” Check your code 😄 “and then see what a mock service looks like that takes just over an hour (*❦ω❦)
project
The technical stack is definitely written using the Node that our big front-end friends are most familiar with, using the KOA framework, and the project effect is as follows:
Teaching people to fish is better than teaching people to fish, so we first principle, after the project code, ha ha ha! Lambda to the minus lambda to the V
Project principle:
Random () : returns a random number between 0 (included) and 1 (not included); Then we’ll wrap a simple function based on this API
/** * @description: //! @param {number} minNum default value 1 * @param {number} maxNum default value 10 * @return {number} */ const randomNum = (minNum = 1, maxNum = 10) => { return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10); }Copy the code
Next is the development of our mock API function. First, we will use an API that randomly produces the title of the article. In order to use it easily, we have set the default value of the range in the function.
/** * @description: //! Random generate title * @param {number} min minimum string interval, Default 10 * @param {number} Max Maximum range of strings, default 30 * @return {string} TMP to generate the content of the title randomly within the specified return */ const randomTitle = (min = 10, Max = 30) = > {the if (min > Max | | min < = 0) {return "the data input is wrong!" ; } let STR = 'Even the wisest man cannot see his own back, he has courage to bear his fate, that is the hero. The more incompetent a man is, the more he finds fault with others. let tmp = ''; let sum = randomNum(min, max); for (let i = 1; i <= sum; i++) { tmp += str.charAt(Math.floor(Math.random() * str.length)); } return tmp; }Copy the code
If you look at this and you think it’s easy to implement this,
Next, we write a random production captcha content:
/** * @description://! * @param {number} min The smallest string interval, Default value 10 * @param {number} Max Maximum range of strings, default value 30 * @return {string} TMP Returns a string within the range * @author: LuKang * / const randomString = (min = 10, Max = 30) = > {the if (min > Max | | min < = 0) {return "the data input is wrong!" ; } let str = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //@ remove confusing character let TMP = ''; let sum = randomNum(min, max); for (let i = 1; i <= sum; i++) { tmp += str.charAt(Math.floor(Math.random() * str.length)); } return tmp; }Copy the code
Random generation of name, random generation of ID card, random generation of remarks, random generation of mobile phone number, random generation of date and time…
Note: The code shown above still has room for optimization and extension
project
The project is based on the KOA framework. The first screenshot you see above is something like the following:
The first is the three-dimensional text display effect of this project, using the alphabetJS dependency package
const Alphabet = require('alphabetjs'); const SymbolLu = Alphabet('SymbolLu', 'stereo'); //@planar, stereo console.log(SymbolLu)Copy the code
The console is white by default, so we use the colors package to change the color of the text printed by the console
const Alphabet = require('alphabetjs'); const SymbolLu = Alphabet('SymbolLu', 'stereo'); //@planar, stereo console.log(symbollu.green)Copy the code
Then there is the output of the interface’s BaseUrl, which is essentially a concatenation of template strings http://${getIPAdress()}:${PORT}
const { PORT } = require('../../config.js');
//!获取ip地址
getIPAdress = () => {
let interfaces = require('os').networkInterfaces();
let ip = '';
for (let devName in interfaces) {
let iface = interfaces[devName];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
ip = alias.address
}
}
}
return ip;
}
Copy the code
We need to configure the routers for interfaces, controllers and routers
const demo = require(".. /controllers/demo")//! /** * @type {custom.irouter} */ module.exports = router => {router. Prefix ("/demo")// Set the route prefix router.post("/", demo.index); Router.get ("/data", demo.index); / / here below the address of the interface to the console interface BaseUrl 】 【 + + routing information routing prefix 】 【 the router / / such as http://192.168.199.15:3000/demo/data. Post ("/possible ", Demo.possibleerror) router.get("/pagingList", demo.paging)// paging}Copy the code
And then let’s look at this controller
module.exports = { /** * @description: */ async index(CTX, next) {const {name, age} = ctx.request.query; / /! Console. log(name, "name") console.log(age, "age") //! Let tel = ctx.random. RandomPhone (); let tel = ctx.random. Let STR = ctx.random.randomString(); Let strName = ctx.random.randomName(); Ctx. success({tel, name, age, STR, strName})}Copy the code
RandomPhone () (context_context) (context_context) (context_context) (context_context) (context_context) (context_context) (context_context) (context_context)
// extend/context.js const context = {} const config = require(".. /config") const random = require(".. /tools/random") const utils = require(".. /tools/utils") context.config = config context.random = random context.utils = utils /** * Successfully returns * @param {any} data * @param {number} status {default: 200} */ context.success = function (data, status = 200) { const statusIsNumber = typeof status === "number" if (! StatusIsNumber) {throw new Error(" status must be number ")} let MSG = 'success'; let code = 1; // add random error code to start let number = context.random.randomnum (); If (number == 8) {MSG = 'fail'; code = 0; this.status = 500 data = []; this.body = {code, msg, status:500, data} } else { this.status = status this.body = {code, msg, status, * @param {obj} data * @param {number} status {default 500} */ context.err = function (data, status = 500) { const statusIsNumber = typeof status === "number" if (! StatusIsNumber) {throw new Error(" return status must be number type ")} this.status = status let MSG = data.msg? data.msg :'fail' this.body = {code:0, msg, status, data } } module.exports = contextCopy the code
Then I imported it in index.js
// idnex.js const { resolve } = require("path") const CustomKoa = require("./custom/app") const context = require("./extend/context") const middlewares = require("./middlewares") const path = require('path') const static = Const cors = require('koa2-cors'); const cors = require('koa2-cors'); // const colors = require('colors'); // Introduce the colors library to set the colors printed in the console const staticPath = './static' const app = new CustomKoa( App.use (cORS (context.config.cors))// Set the cross-domain processing app.usemiddlewares (middlewares)// register middleware // Set the Theme of the console to colors.setTheme(context.config.theme); app.useRouters(resolve(__dirname, "./routers")) app.use(static(path.join(__dirname, App.extendcontext (context) module.exports = {server: app}Copy the code
The mock services are the core code (# ^. ^ #), although at the time of his hand rolled the mock services, satisfy the front-end team we use at the time, after all, when the last company is only six front end use, to a certain extent, improve the efficiency of our work, have more fishing (learning), But it still has a lot of shortcomings, after all, this was only an internal use of the project, for internal use and development of the project address complete code point here
Note: since the previous complete project involves the content of the company, here is a truncated version of demo service for building, if you are interested, you can enrich and expand yourself!
Pain points for mock data
With mock services out of the way, let’s take a closer look at mock services. Although the mock data to a certain extent, can improve the efficiency of our development, but we still need to spend a certain amount of time to write a mock data, even if we already have so many mock tool, as much as we talk on the mock solution, but they are also there is a problem, the problem is, Mock data is the same data as the interface document. Mock data is the same data as the interface document. Well, of course, people are lazy, now, we have added a spot, is the need to according to the data interface document to mock ≡ ┏ | * ´, Д, | ┛ that this pain points, solutions, and I feel we front mock data of the final solution, Instead of having to mock manually, it would be more efficient for the tool to mock automatically based on our interface documentation, and then we’ll talk about the ultimate pain point solution
Solutions to pain points
Apifox (Opens New Window) is a platform for API documentation, API debugging, API Mock, and API automated testing, targeting Postman + Swagger + Mock + JMeter.
Based on the above pain points, until the author realized that the development (testing) tool, is really a perfect solution, it is Apifox, the official gave a simple formula, more can explain what Apifox can do.
Apifox = Postman + Swagger + Mock + JMeter
It solves the data synchronization problem among multiple systems by using one set of systems and one piece of data. Once the API documentation is defined, API debugging, API data Mock, and API automation testing can be used directly without further definition. API documentation and API development debugging use the same tool, API debugging can be guaranteed to be exactly the same as the API documentation definition. Efficient, timely and accurate! Very powerful development tools hahaha, in a word Apifox awesome
ApifoxFeatures:
- Apifox complies with OpenApi 3.0 (original Swagger), JSON Schema specifications at the same time, provides a very easy to use visual document management function, zero learning cost, very efficient.
- Interface debugging: Postman has some functions, such as environment variables, pre-execute script, post-execute script, Cookie/Session global sharing and other functions, Apifox also has, and is the most important Chinese interface developed by Chinese people.
- Data Mock: The built-in mock. js rule engine makes it easy to Mock out various types of data and write Mock rules while defining data structures. You can add Expectations and flexibly return different data content based on parameter values. The most important thing is that Apifox can Mock out very humanized data with zero configuration, which is also the focus of this article. After the backend interface document is written, the front-end Mock data is available.
- Interface automation testing: Provides interface collection tests that can be quickly created by selecting an interface (or interface use case). At present, more functions of interface automation testing are still under development. The goal is to have all the functions of JMeter and make it better.
- Team collaboration: Apifox is born for team collaboration, with real-time cloud interface and mature team/project/member rights management to meet the needs of various enterprises
Of course, we’re talking about its ability to Mock data,
Use notes
At first we team (the place in the team) back-end after every time to write the interface document also need to the front to build data (mock data), our company’s front end is car-scrapping, back-end students make mock data 😄, back-end students also need to spend some time to write a script, after all, the development of the project time is very tight, so we want to, So we migrated the interface document to Apifox and used it to manage the interface document. The backend only needed to design the interface document, set the type, and use its mock service. Sass will automatically generate the mock data service we need, no longer need to write mock services manually. Most importantly, the public network based version of SASS is free, so this article is to share with you.
Article history
- How can you make your code more elegant
- Talk about arrays in JS
- Using Plain English to handle regular easily (PART 1)
- Using plain English to easily solve the regular (2)
- Learn redraw and refluxing together
- Js garbage collection mechanism principle to you talk clearly
- ES11 is here. Why don’t you check it out
- Second understand js scope and scope chain
conclusion
The above is all the content of this article, I hope to help you, there is no need to reward ha, you can give a praise 👍 (praise and do not have money), also welcome everyone forward