Using JavaScript with API tests

You can handle complex API testing and troubleshooting scenarios using JavaScript code that can be supplied within the following parts of an API test step:

  • Pre-request script - code runs before the request is made to execute conditional logic
  • Tests script - code runs after the request is made to validate response data

Thanks to the mabl integration with Postman, you can use any Postman-supported JavaScript objects and functions to handle your custom logic and response validations. Let's run through some examples.

🚧

Test size limits

Please note that API tests cannot exceed 1MB in size. We recommend using caution with large JavaScript pre-request scripts.

Response validation

Rest APIs with JSON payloads

To validate data in a response JSON body, you can use code like the one below:

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); 
});

To validate the length of an array, you can add the following snippet inside of the above pm.tests() function: pm.expect(responseJson.person).to.have.lengthOf(15);

In the above example, if the person's name you want to assert against is stored in a variable such as personName you can simply replace the static string "Jane" with a variable value so that the code for that assertion looks like this: pm.expect(responseJson.person[3].name).to.eql(pm.variables.get("personName"));

SOAP APIs with XML payloads

You can use the following scripting approach to create assertions that validate data in an XML-based response body.

First, you need to convert the XML body to a JSON object using the built-in xml2json library. Then, you can use JSON path notation or iterate over the object keys to find the target property you would like to assert on.

For example, let's send a POST request to the following endpoint https://www.w3schools.com/xml/tempconvert.asmx that conversts temperature from Fahrenheit to Celsius degrees. We will use one variable (e.g. tempF = 32) to pass the Fahrenheit input in the body of the request and use a second varaible to validate that we get the expected Celsius result (e.g. tempC = 0) in the response body. Here's what you need to enter for the API test step:

Method: POST
URL: https://www.w3schools.com/xml/tempconvert.asmx
Headers:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
     <FahrenheitToCelsius xmlns="https://www.w3schools.com/xml/">
       <Fahrenheit>{{tempF}}</Fahrenheit>
     </FahrenheitToCelsius>
    </soap:Body>
</soap:Envelope>

When you send that POST request, you should get a response body with the tempeture degrees in Celsius (e.g. 32°F converts to 0°C).

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <FahrenheitToCelsiusResponse xmlns="https://www.w3schools.com/xml/">
      <FahrenheitToCelsiusResult>0</FahrenheitToCelsiusResult>
    </FahrenheitToCelsiusResponse>
  </soap:Body>
</soap:Envelope>

To assert that the <FahrenheitToCelsiusResult>0</FahrenheitToCelsiusResult> value equals the value of the tempC variable, you can write the following script in the Validation and variable assignment section of the API step.

pm.test("Validate conversion Fahrenheit To Celsius produces the expected result", () => {
    //convert XML response body to a JSON object using xml2Json library
    const responseJson = xml2Json(pm.response.text());

    //Use JSON path syntax to get to the target property 
    let result = responseJson["soap:Envelope"]["soap:Body"].FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult;

    //Assert that result is the correct value
    pm.expect(result).to.eql(pm.variables.get("tempC"));
});

Variable creation

Creating variables based on JSON data

You can create variables based on an API response in (JSON) using code that looks like the following:

var jsonData = JSON.parse(responseBody);

//assign the third person's object id to a variable named userID
postman.setEnvironmentVariable("userID", jsonData.person[3].id);

Creating variables based on XML data

To create a varaible based on an API response body in XML format, you first need to convert the XML body to a JSON object using the built-in xml2json library. Then, you can use JSON path notation or iterate over the object keys to find the target property value that you want to assign to a variable.

For example, let's use the API endpoint described in the assertion section above that that conversts temperature from Fahrenheit to Celsius degrees. You can assign the resulting Celsius degrees to a variable called myTemperature with the following script.

//convert XML response body to a JSON object using xml2Json library
const responseJson = xml2Json(pm.response.text());

//Use JSON path syntax to get to the target property value to be assigned to a variable
let result = responseJson["soap:Envelope"]["soap:Body"].FahrenheitToCelsiusResponse.FahrenheitToCelsiusResult;

//Assign the result value to a given variable name
pm.environment.set("myTemperature", result);

The variable creation script is very similar to the assertion script in the prior section. The main difference is the target value is being assigned to a variable instead of being validated with an assertion.

In order to see the updated myTemperature variable value when you send the request, you can add myTemperature to the variables list in the left side pannel of the API test editor.

Available JavaScript libraries

There are a number of JavaScript libraries and Node.js modules that you can take advatange when doing API testing with mabl. The availability of these libraries is thanks to the mabl integration with Postman and as such you should be able to work with them as if you were using Postman, for the most part.

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

Please, refer to the Postman documentation for complete scripting reference.


Did this page help you?