Abstract: When doing interface testing, some interfaces need to carry out a large number of data for testing, but also can not be repeated data, this time it needs random production data for testing. Here you are taught to use mock.js to generate various random data.

What is mock.js

Mocking.js is used to generate random data to intercept Ajax requests. By intercepting Ajax requests, generating and returning mock data from data templates, the front end batchers develop independently of the back end and help write unit tests.

1. Increase the authenticity of unit tests. Using random data, various scenarios are simulated.

2. Non-invasive development. You can intercept the Ajax request and return simulated response data without modifying the existing code. Intuitive interface that is simple to use.

3. Rich data types. Support to generate random text, numbers, Boolean values, dates, mailboxes, links, pictures, colors, and so on.

4, easy to expand. Support for extending more data types, support for custom functions and re

5. Summary. Because mock.js can produce a variety of data data, it can also be used on interface tests to generate various interface parameter values.

How to use mock.js in apipost

Apipost has built-in mock field variables

When you need to use a variable, copy the variable name directly to the parameter value, as shown in the figure:

Write a custom mock.js variable in the execution script

Such as:

1) Create a random phone number and paste it into the execution script and set an environment variable with the value of the phone number as the data produced:

Const phonePrefix = [‘ 132 ‘, ‘135’, Var phone = phonePrefix[index] + Mock. Mock (/d{8}/) Apt. Variables. The set (” phone “, phone);

Reference set variables, as shown in the figure;

2) Produce a random timestamp

Var timestamp= date.parse (new Date()) apt.variables. Set (” timestamp “, timestamp);

Reference random time stamps

If you want to go deeper into mock.js, you can go to the mock.js website.

This article is from the Huawei Cloud community interface testing – Using Mock to produce random data.

Click follow to learn about the fresh technologies of Huawei Cloud