In mabl, you can create custom scripts for API tests by combining one or more API snippets. Whenever possible, we recommend using our low-code functionality for creating assertions and variables. By limiting the use of custom snippets only to more complex scenarios, you can ensure that the results of your test are easy to view and maintain by all members of your workspace.
This article outlines how to accomplish several common tasks in an API snippet:
Many of these examples make use of the Postman JavaScript object, which is available through the mabl integration with Postman.
Working with XML payloads
If you are working with an API that uses XML payloads, refer to the article on working with XML payloads for more information.
Access variables
To use an existing variable from the test in an API snippet, use pm.variables.get(). For example:
// get the value of "new_user_id" and store in variable newUserId
let newUserId = pm.variables.get("new_user_id")
// log the value of newUserId to the console
console.log(`The new user's ID is ${newUserId}`);To access flow parameters within a snippet, use pm.variables.replaceIn(). For example:
// get the value of "product_id" flow parameter and store in variable productId
let productId = pm.variables.replaceIn('{{flow.product_id}}')
// log the value of newUserId to the console
console.log(`The product ID is ${productId}`);Validate a response
To validate a JSON body response, use pm.expect(). For example:
pm.test("Person is Jane", () => {
//assigning the response body to a constant.
const responseJson = pm.response.json();
//assert that the third person object in the response has name and age properties with a given value.
pm.expect(responseJson.person[3].name).to.eql("Jane");
pm.expect(responseJson.person[3].age).to.eql(23);
// assert that the second person object in the response as the name properties of the variable "personName"
pm.expect(responseJson.person[3].name).to.eql(pm.variables.get("personName"));
// validate the length of an array
pm.expect(responseJson.person).to.have.lengthOf(15);
});Create a variable
To create a variable based on a JSON response, use pm.environment.set(). For example:
var jsonData = JSON.parse(responseBody);
//assign the third person's object id to a variable named userID
pm.environment.set("userID", jsonData.person[3].id);Run console logs
Console logs are useful for debugging. The following log statements are supported:
- console.log()
- console.info()
- console.warn()
- console.error()
The output of your console log statements is visible in the API Test Editor, API test output page for cloud runs, as well as the output of local runs via the CLI.
Learn more
For more information on Postman methods, please refer to official documentation in Postman.