“Quality is not an act, it is a habit.”
Introduction: Pain Points of Frontend Development
During project development, frontend and backend are usually developed in parallel. But we often encounter the following awkward situations:
- Backend interfaces are not ready: The backend is still writing CRUD operations, while the frontend pages are already cut, but can only be filled with dummy data.
- Hard to reproduce exception scenarios: Wanting to self-test “server returning an empty list” or “extra-long text truncation” requires backend cooperation to modify the database, which is very troublesome.
- Incomplete data coverage: The cost of fabricating data in the test environment is high, sometimes even requiring dropping the database and rerunning.
This is where Local Mocking technology comes in handy. By intercepting requests at the network layer, we can run a simple piece of code to modify the Response (response body) in real-time, tricking the client into thinking the server returned the data we wanted.
Core Principle: Man-In-The-Middle (MITM) Scripts
Most professional network debugging tools (like Charles, Fiddler, Proxyman) support a Scripting feature.
The process is as follows:
- Intercept: The tool captures a specific URL request (e.g.,
api.myapp.com/user). - Execute: The tool runs the
.jsscript you wrote. - Modify: The script reads the original Response JSON and modifies specific fields.
- Return: The client receives the modified data.
JavaScript Scripting Practice
The core logic of the script is usually divided into three steps: Parse -> Modify -> Stringify.
Scenario 1: Mocking Long Text (Testing UI Layout)
Suppose the standard user info returned by the backend is as follows:
{ "id": 101, "nickname": "Levi", "bio": "Frontend Developer"}We need to test whether the UI properly wraps or shows an ellipsis when the user nickname is exceptionally long.
Script Code Example:
// 1. Get original response body// Most tools expose the response body as response.body or a similar variablelet obj = JSON.parse($response.body);
// 2. Modify data: inject extra-long text to test edge case UI behaviorobj.nickname = "This is a very, very long test text, intended to verify if the UI component's layout behavior is normal under extreme conditions.";
// 3. Stringify and return// Convert the modified object back to a string$done({ body: JSON.stringify(obj) });Scenario 2: Simulating Server Errors (Testing Robustness)
The App needs to gracefully handle server errors (like 500 errors or network timeouts). We can write a script to force a normal successful response into an error message.
Script Code Example:
// Note: This time we don't parse the original data, we construct the error response directly
let errorResponse = { "code": 500, "status": "error", "message": "Internal Server Error: Simulated server internal error"};
$done({ status: 500, // Modify HTTP status code body: JSON.stringify(errorResponse)});Advanced Tips: Conditional Breakpoints and Randomization
To test more realistic scenarios, we can introduce random logic to simulate unstable data returns.
let obj = JSON.parse($response.body);
// Randomly generate a 50% probability to make the list empty, testing the "Empty State" pageif (Math.random() > 0.5) { obj.data_list = [];}
console.log("Current Mock Status: " + (obj.data_list.length === 0 ? "Empty List" : "Has Data"));
$done({ body: JSON.stringify(obj) });Best Practices and Precautions
- Exception Catching: When parsing JSON, it is best to wrap it in a
try-catchblock to prevent script errors caused by parsing failures of the original data.try {let obj = JSON.parse($response.body);// ... modifications$done({ body: JSON.stringify(obj) });} catch (e) {console.log("JSON Parse Error: " + e);$done({}); // Keep original state} - Only Use for Development Self-Testing: Such scripts should only be used in local development or test environments, and are strictly prohibited in production environments or for malicious attacks.
- Only Handle Authorized Traffic: Please ensure you are intercepting and debugging applications you are responsible for, test domains, or authorized APIs. Do not touch unauthorized third-party systems.
- Avoid Real User Data: The debugging environment should use desensitized data as much as possible to avoid exposing sensitive information like phone numbers, emails, and Tokens in scripts, logs, or screenshots.
Summary
Mastering network-layer Mocking technology based on scripts can vastly reduce frontend development’s dependency on the backend. You don’t need to wait for backend deployment, nor do you need to ask people to change data. With a few lines of code, you can construct any test scenario you want, greatly improving development efficiency.
Happy Coding!
If this article helped you, please share it with others!
Some information may be outdated





