mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
520 words
3 minutes
Frontend Development Practice: How to Use Charles Scripts for API Data Mocking
2023-12-22

“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:

  1. 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.
  2. 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.
  3. 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:

  1. Intercept: The tool captures a specific URL request (e.g., api.myapp.com/user).
  2. Execute: The tool runs the .js script you wrote.
  3. Modify: The script reads the original Response JSON and modifies specific fields.
  4. 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 variable
let obj = JSON.parse($response.body);
// 2. Modify data: inject extra-long text to test edge case UI behavior
obj.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" page
if (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#

  1. Exception Catching: When parsing JSON, it is best to wrap it in a try-catch block 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
    }
  2. 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.
  3. 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.
  4. 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!

Share

If this article helped you, please share it with others!

Frontend Development Practice: How to Use Charles Scripts for API Data Mocking
https://blog.levifree.com/posts/javascript-mock-api-tutorial/
Author
LeviFREE
Published at
2023-12-22
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents