Postman is one of the most popular interface testing tools in the front-end community. Most developers use only the most basic functions, which are requests and responses. However, Postman provides developers with more than that. There is a pre-Request script before the Request and a test script after the response. Together, these four parts make up a complete Postman workflow.
Request and Response I believe we can use, here mainly introduces the use of pre-request script and test script, to login interface as an example, demonstrate a Postman workflow complete application scenario.
Pre-request script
A pre-request script is a script that is executed before sending a request. So what does this script do? Look at this requirement:
Add a timestamp field to each request parameter to record the current send time.
You might want to disable this parameter in Postman, but you can dynamically generate the current timestamp every time you send a request by adding the following code to your pre-request script:
pm.environment.set("timestamp", Date.now())
Copy the code
This generates a timestamp environment variable that can be referenced by {{timestamp}} in Params, Headers, and Body Postman. {{$timestamp}}, {{$randomInt}}, ${{$randomPhoneNum}} and other system environment variables, can be called at any time.
Of course, most of the time, we still want to be able to define our own environment variables. For example, in the login interface, I put a lot of test login accounts in the pre-Request script, which can be switched at any time. It is very convenient:
Once the body environment variable is set, it can be retrieved from the request body with {{body}} :
Test script
Postman has built in a set of testing rules and integrated with the TV4 testing framework to make it easy for developers to verify the results upon receiving a request, such as:
// Get the JSON response body
var jsonData = pm.response.json()
// Make sure the status code is 200 and value is 100
pm.test("value is 100".function () {
pm.response.to.have.status(200)
pm.expect(jsonData.value).to.eql(100)})Copy the code
For example, we need to delete the body variable in the pre-request script, otherwise it will remain in the Postman environment variable forever:
// Delete the dynamically created body
postman.clearEnvironmentVariable("body")
Copy the code
There is an accessToken field in the return result of the login interface that we need to reserve for subsequent requests:
// Extract the token from the response body and write the environment variable
var token = jsonData.accessToken
if (token) {
pm.environment.set("token", token)
}
Copy the code
The entire script reads as follows: