You can handle complex API testing and troubleshooting scenarios using JavaScript code.
Use cases
Using scripts in an API test can be useful in the following situations:
- Extracting data from a response in a specific way that requires multiple lines of code
- Handling specific authentication scenarios, such as getting authentication tokens from third party APIs or checking if auth tokens need to be renewed
- Executing specific cleanup code after every request in the test
- Creating assertions or variables from an XML-based response body
- Running console logs for debugging purposes
The API Test Editor supports ECMAScript 8.
Postman JavaScript object
Thanks to the mabl integration with Postman, you can use Postman-supported JavaScript objects and functions to handle your custom logic and response validations.
As a best practice, we recommend using the API Test Editor to write your tests whenever possible and limiting the use of Postman methods to handle more complex scenarios. Tests that don’t use, or make sparing use of, scripts are recommended for two reasons:
-
They are easier for all members of a workspace to understand and maintain.
-
Their results are easily viewable from the UI.
For working examples, see the API script examples guide.
Please note that API tests cannot exceed 1MB in size. We recommend using caution with large scripts.
Available JavaScript libraries
Mabl's integration with Postman also makes it possible to use a number of JavaScript libraries and Node.js modules:
JavaScript libraries
- ajv
- atob
- btoa
- chai
- cheerio
- crypto-js
- csv-parse/lib/sync
- lodash
- moment
- postman-collection
- tv4
- uuid
- xml2js
Node.js modules
- path
- assert
- buffer
- util
- url
- punycode
- querystring
- string-decoder
- stream
- timers
- events
You can use the require()
method to call one of those libraries. Here is an example of using the moment
library to generate a future date that is seven days from today.
let moment = require('moment');
//get a date that is N number of days from today
let date = moment.utc().add(7, 'days').toJSON();
//specify desired date and time format
let dateFormat = "MM-DD-YYYY"
//format the date and assign it to a variable to be used in other API requests and tests
pm.environment.set("futureDate", moment(date).format(dateFormat));
Learn more
To learn how to add a script to a mabl API test, click here.
To see specific examples of how to use JavaScript in an API test, refer to the API script examples guide.