Original address
Introduce
Mock (simulation): is an object/interface that is external to the project or not easily accessible in project testing.Simulate with a virtual object/interfaceFor testing.
background
Front and back end separation
-
Front and back ends are programmed only through asynchronous interfaces (AJAX/JSONP)
-
Each front and back end has its own development process, build tools, and test set.
-
Separation of concerns, front and back ends becoming relatively independent and loosely coupled
Development process
-
Write and maintain interface documents in the background, update interface documents when API changes
-
Background interface development based on interface documents
-
The front end is developed according to the interface document
-
Debugging and submitting tests after completion of development
Facing problems
-
Documents are becoming more and more confused and can not be maintained and read without a unified specification for document writing.
-
In the development of the interface changes, such as add, delete and modify, need greater communication costs.
-
For a new requirement, the front-end interface calls and self-test dependencies are developed in the background.
-
Delay project time by postponing interface risks
Resolvent
-
Interface Document Server–Solving the Editing and Maintenance of Interface Documents
-
Mock data — resolving the problem of front-end development relying on real back-end interface
Interface Document Server
function
Interface editing function
-
Type 1: Write the interface according to the interface description grammar and save it as a text file, then use the generation tool to generate the online document (HTML)
There are also some Markdown-like interface document editors, see: There Are Four API Design Editors To Choose From Now.
-
Type 2: Provide an online interface editing platform for interactive interface editing
Interface Viewing Function
-
Provide friendly interface document viewing function
usage
-
Background developers write interface documents
Define interface path, interface upload field, interface return field, field meaning, field type, field value -
Front-end developers view interface documents
Advantage
-
Unified Management and Maintenance of Interface Documents
– Provides interface import, interface modularization, interface versioning, visual editing and other functions. -
The interface document is standard and readable.Reduce front-end and back-end interface communication costs
Review of Front-end Mock Method
In the front-end development process, mock data is used to simulate the return of the interface and test the business logic of the developed code. Solve the dependence on the background interface in the development process.
Hardcoded data
Write mock data in code.
Example
// $.ajax({
// url: ‘https://cntchen.github.io/userInfo’,
// type: 'GET',
// success: function(dt) {
var dt = {
"isSuccess": true,
"errMsg": "This is error.",
"data": {
"userName": "Cntchen",
"about": "FE"
},
};
if (dt.isSuccess) {
render(dt.data);
} else {
console.log(dt.errMsg);
}
// },
// fail: function() {}
// });
Advantage
-
Quick modification of test data
Pain spot
-
Unable to simulate asynchronous network request, unable to test network exception
-
Dirty code, need to make more changes before debugging.Increase the switching cost of the final real environment
Adding network requests, modifying interfaces, and adding error control logic -
Interface document changes need to be updated manually
Request interception & mock data
The network request of hijack interface replaces the return of the request with the mock data in the code.
Example
jquery-mockjax
The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses
Advantage
-
Can simulate asynchronous network requests
-
Quick modification of test data
Pain spot
-
Depending on a specific framework, such as
Jquery
-
Increase the switching cost of the final real environment
-
Interface document transformation needs to be updated manually
Local mock server
Save mock data as a local file. In the construction flow of front-end debugging, the local mock server is opened with node, and the request interface points to the local mock server and the local mock server response mock file.
Mock file
.mock
├── userInfo.json
├── userStars.json
├── blogs.json
└── following.json
Interface call
https://github.com/CntChen/userInfo
–> localhost:port/userInfo
Advantage
-
With minor code changes, debugging tests only need to change the interface URL
-
Quick modification of test data
Pain spot
-
There are many JSON files
-
Interface document changes need to be updated manually
proxy server
-
Use Charles or Fiddler as proxy server
-
Map (mapping) using proxy server & rewrite (rewrite) function
map local
-
The return of the interface request is mapped to local mock data
https://github.com/CntChen/userInfo
–>localPath/userInfo
-
Edit mapping rules
map remote
-
The return of the interface request maps to the call of another remote interface
rewrite
-
Modify the request or response of the interface call, add/delete/modify HTTP
request line
/response line
/headers
/body
-
Solving cross-domain problems
With map, the response invoked by the interface does not have CORS headers, and cross-domain requests will report errors on the browser side. You need to rewrite the header returned by the interface to add the CORS field.
Advantage
-
The front end directly requests the real interface without modifying the code
-
You can modify the interface to return data
Pain spot
-
Cross-domain issues need to be addressed
-
A change requires multiple changes in the proxy server, which is inefficient to configure.
-
Differentiation of HTTP methods is not supported
— CORS preflight request (OPTION) also returns data -
Need a remote interface or local mock file, the same pain point as using a local mock file
Mock platform
Interface Document Server
Using Interface Document Server to Define Interface Data Structure
Mock server
Mock server automatically generates mock data according to interface documentsThe interface document, API, is implemented.
Advantage
-
Automatic generation and update of mock data for interface documents
-
Small changes in front-end code debugging
shortcoming
-
ProbablyThere are cross-domain problems
Industry practice
Company practice
No company-level framework was found, except for Ali’s RAP. Possible reasons:
-
Non-critical, pioneering technology, not much research value
-
Many large companies are small teams, and there is no unified mock platform.
-
There are already some stable interfaces, and there is no problem that the back-end interface has not been developed.
And the question we want to explore is: front and back endsSimultaneous developmentMock
GitHub open source library
-
faker.js
Random generation of mock data for fixed fields, such asemail
,date
,images
To support internationalization. -
blueprint
A powerful high-level API design language for web APIs.
An interface programming language using markdown-like grammar, using json-schema and mson as interface field descriptions. There are perfect tool chains for interface files such as Edit, Test, Mock, Parse, Converter, etc.
-
swagger
Swagger is a simple but powerful representation of Rest API, standard, language-independent, which is not only human-readable, but also machine-readable. It can be used as an interactive document of Rest API or as a formal interface description of Rest API to generate client and server code. –Swagger: Description Language for Rest API
A set of interface document writing grammar is defined, and then the interface document can be automatically generated. Related projects: Swagger Editor, for writing API documents. Swagger UI restful interface document online automatic generation and function testing software. Click on the Swagger-UI online example.
-
wireMock
WireMock is a simulator for HTTP-based APIs. Some might consider it a service virtualization tool or a mock server. It supports testing of edge cases and failure modes that the real API won’t reliably produce.
Commercialization programme
-
apiary
Business Solution, Creator of Blueprint Open Source Project. Interfacing, providing mock functionality, generating call codes for each programming language (similar to postman’s generate code snippets).
Other practice
API Evangelist
summary
For front-end and back-end separated development methods, there are mature mock platforms, which mainly solve two problems:
-
Editing and Maintenance of Interface Documents
-
Automatic generation and update of interface mock data
Epilogue
Pre-research time is limited. Some new mock models or excellent mock platforms are not covered. Welcome to add.
The platform chosen by the author’s company is RAP, and a RAP practice article will be sorted out in the future.
The question arises: What is the mock approach you are developing?
References
-
Graphic front-end and back-end separation based on node.js
http://yalishizhude.github.io…
-
TestDouble (introducing mock related concepts)
http://martinfowler.com/bliki…
-
There Are Four API Design Editors To Choose From Now
https://apievangelist.com/201…
-
The Pain of Synchronization–Contract Testing
http://www.ituring.com.cn/art…
-
Swagger: Description Language for Rest API
https://zhuanlan.zhihu.com/p/…
-
Swagger – Front-end and Back-end Separated Contracts
http://www.cnblogs.com/whitew…
-
Swagger UI Tutorial API Document Artifact Matched with Node
http://www.jianshu.com/p/d662…