# Execute JavaScript

Users can now write JavaScript code to perform math operations, string operations using API’s response.

The idea here is to provide math operations and string operations functionalities under pre-requisite and assertions as a form of javascript code where users can use Json paths of current API response or normal hardcoded values to perform operations.

JavaScript code examples :

```
Note: Please follow ES5.1 syntax, Rules, and Functions for writing javascript code.
```

***

## Contents

* [Execute JavaScript](#execute-javascript)
  * [Math Operations](#math-operation)
  * [String Operations](#string-operation)
  * [Steps to test Execute JavaScript:](#steps-to-test-execute-javascript)
  * [Related topics](#related-topics)

***

### Math operation

* This supports all Arithmetic operations such as + , - , \* , / , % . Code for all operations will remain the same except symbols. Examples listed below

  *Input* :

  ```
    var executeJs = function(response,headers){
        var x = 10;
        var y = 20;
        var z = x * y;
        return z;
    }
  ```

  *Output* :

  ```
    200.0
  ```

  **Note 1:** In order to get integer response of above operation use “toFixed(0)” in above code like below -

  ```
    var executeJs = function(response,headers){
        var x = 10;
        var y = 20;
        var z = x * y;
        return z.toFixed(0);
    }
  ```

  *Output* :

  ```
    200
  ```

  **Note 2:** Users are not allowed to change line 1, They can only add respective JavaScript code in between {} example given below.

  **Good :**

  ```
    var executeJs = function(response,headers){
    //your JavaScript code here
    }
  ```

  **Bad :**

  ```
    var testing= function(test1, test2, test3){
    //your JavaScript code here
    }
    var myJsFunction= function(){
    //your JavaScript code here
    }
  ```

***

### String operation

* This operation support all String operations like concat, substring, equals etc. Code for all operation will remain same except mode of operations. Examples listed below

  **Input :**

  ```
    var executeJs = function(response,headers){
        var mySrting = "this is my string example";
        var substring = mySrting .substr(19, 7);
        return substring;
    }
  ```

  **Output :**

  ```
    example
  ```

  **Input :**

  ```
    var executeJs = function(response,headers){
        var mySrting1 = "My name is ";
        var mySrting2 = mySrting1.concat("Alpha");
        return mySrting2;
    }
  ```

  **Output :**

  ```
    My name is Alpha
  ```

  **Input :**

  ```
    var executeJs = function(response,headers){
        var mySrting1 = "My name is";
        var mySrting2 = "This is second string";
        if(mySrting1.equals(mySrting2)){
        return "both string are same";
        }
        else{
        return "different strings";
        }
    }
  ```

  **Output :**

  ```
    different strings
  ```

  **RegEx example :** my API response is having this string in it “code%test\_user\_1234%”

  **Input :**

  ```
    var executeJs = function(response,headers){
        var str = response.toString();
        //this pattern is used to find first occurance of string which is present in the form like this %My_string% in the response
        var regExp = /(code%[\\w\\d\\W]+%)/g
        var match = regExp.exec(str);
        var sub = match[1];
        return sub.substr(5,14);//this can be alterd based on use case
    }
  ```

  ***Output :***

  ```
    test_user_1234
  ```

***

### Using Json paths

* This operation used to fetch Json path values and perform math or string opertaions.
* For this example took reference of this post API from petstore
  * API : “<https://petstore.swagger.io/v2/pet”>
  * Verb Type : POST

#### Math operation input :

* In my case id & category.id contains value “10” respectively.

  ```
    var executeJs = function(response,headers){
        var x = JSON.parse(response);
        var response2 = x.id;
        var response1 = x.category.id;
        var result = response2 * response1;
        return result;
    }
  ```

  **Output :**

  ```
    100.0
  ```

#### String operation input :

* In my case photoUrls\[0] & tags\[0].name contains value “String” respectively.

  ```
    var executeJs = function(response,headers){
        var x = JSON.parse(response);
        var response2 = x.photoUrls[0];
        var response1 = x.tags[0].name;
        var result = response2.contains(response1);
        return result;
    }
  ```

  **Output :**

  ```
    TRUE
  ```
* Say response is having multiple index of same value then follow below example :

  **Input :** In my case both values are different.

  ```
    var executeJs = function(response,headers){
        var x = JSON.parse(response);
        var response = x[10].photoUrls[0];
        var response1 = x[5].tags[0].name;
        var result = response.contains(response1);
        return result;
    }
  ```

  **Output :**

  ```
    FALSE
  ```

  *Note :* Current JavaScript implementation does not support any import Node.js of liberates such as console, window etc.

  **Example input :**

  ```
    var executeJs = function(response,headers){
        var x = 5;
        var y = 2;
        var z = x + y;
        console.log(z);
    }
  ```

  Output :

  ```
    "Exception in thread "main" javax.script.ScriptException: ReferenceError: "console" is not defined in <eval> at line number 5"
  ```

***

## Steps to test Execute JavaScript:

Step-1: Navigate to Functional Testing.

Step-2: Step-2: Build a Test Script.

* [Click on to getting started with building a Test Script](/api-testing/functional-testing/build-test-script.md)

Step-3: Click on **Assertion** tab then click on **Json Path Assertion**.

![Assertion](/files/rtVmP0F8dAsHCXV8xMVI)

Step-4: Select **javascript** as type and enter your code.

![Code](/files/HP10OlGfKKcXlHicf9LK)

Step-5: **Save** and **Run** the script.

* Results for Execute Javascript would be like as :

  ![Code](/files/kE6is3ZpFDMchk5EDsGl)

***

### Related topics

* [API To DB Assertion](/api-testing/functional-testing/api-to-db.md)
* [Emailing & Downloading Report](/api-testing/advanced-features/emailing-and-downloading-report.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.qyrus.com/api-testing/advanced-features/execute-javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
