JavaScript API


Overview

The JavaScript APIs can be called from within script actions or JavaScript expressions passed-in as test action arguments anywhere in a test file. Some APIs only make sense in a specific context (e.g. using the $macroArgs and $macroOutput APIs only makes sense inside of a macro action).

All JavaScript APIs exposed by OpenTest are prefixed with $ to make them easily recognizable and to avoid naming conflicts with any user-defined functions and variables.

API list

$array(arrayLike)

Converts the provided argument to a native JavaScript array. Useful when we need to quickly and easily convert a Java collection type to a JS array, so we can access the JavaScript Array APIs (map(), filter(), etc.)

The $array() function currently accepts Java arrays and any objects implementing the Java List interface. If a different object type is passed to the $array function, it will return a new JS array that has the provided object as its only element.

Example:

- script: |
    var ArrayList = Java.type("java.util.ArrayList");

    var myList = new ArrayList();
    myList.add("red");
    myList.add("green");
    myList.add("blue");

    // To use the JS-native Array.join(), we need to first
    // pass the ArrayList instance through $array()
    var colors = $array(myList).join(", ");
    $log("The colors are " + colors);

$base64(inputValue)

Encodes the specified input value to a Base64 string. The data type of the input value can be one of the following:

  • a Java InputStream

  • a Java or JavaScript string

  • a Java native byte array

  • a JavaScript number array

Example 1:

- description: Encode a JavaScript number array
script: |
    var data = [65, 66, 67, 68, 69];
    $log("The Base64 encoded JS array is " + $base64(data));

Example 2:

- description: Encode a Java InputStream
  script: |
    var ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
    var JavaString = Java.type("java.lang.String");

    var myString = new JavaString(
    "This is a sample string that will be encoded to Base64");
    var stream = new ByteArrayInputStream(myString.getBytes("UTF8"));
    $log("The Base64 encoded InputStream is " + $base64(stream));

$config(propertyName)

Reads and returns a configuration property from the test actor configuration file ("actor.yaml"). Properties located at level 2 or deeper in the document hierarchy can be read using dot notation. If the specified property doesn’t exist, the returned value will be null.

Example:

- script: |
    var browserName = $config("selenium.desiredCapabilities.browserName");

$data(relativePath)

Reads a YAML or CSV data file in the test repository and returns a JavaScript object that represents the contents of the data file. The relativePath parameter is the path to the data file, relative to the data directory in the test repository. For YAML files, specifying the .yaml extension is optional. For example, let’s assume we have a data file named person.yaml located directly in the test-repo-path/data directory that stores details about a person, with the following content:

test-repo-path/data/person.yaml
name: John Doe
address:
  city: Oak Brook
  zipCode: 60532

In this case the following syntax can be used in a script action to make use of the data in this file:

- script: |
    $log($data("person").name); // John Doe
    $log($data("person").address.zipCode); // 60532

Please note that, when using the "environments" feature, the data files in the data directory will be overridden by the data files in the environment we are currently running against, if a data file with that name is present for that environment under the data-env directory. More details in the documentation of the environments feature.

$decrypt(encryptedText)

Decrypts the provided encrypted text, using the password that was previously configured for the test actor that is executing the function. The encryption password can be defined in the actor.yaml file through the encryptionPassword configuration parameter, or by setting the OPENTEST_ENCRYPTION_PASSWORD environment variable.

- script: var decryptedSecret = $decrypt("o7//IP1S9Rn0nXWK8g72IA==");

$delay(milliseconds)

Makes the test actor wait for the number of milliseconds specified.

As a best practice, avoid using this API, unless you absolutely have to. Instead, rely on the logic incorporated into the Selenium and Appium keywords, which automatically waits for an element to become visible in the current page or screen. This way, you avoid introducing unnecessary wait times and improve execution speed.

- script: $delay(2000); // Wait for two seconds

$encrypt(text)

Encrypts the provided text, using the password that was previously configured for the test actor that is executing the function. The encryption password can be defined in the actor.yaml file through the encryptionPassword configuration parameter, or by setting the OPENTEST_ENCRYPTION_PASSWORD environment variable.

- script: var encryptedSecret = $encrypt("secret");

$env(varName)

Gets the value of the specified environment variable. Internally, it uses the System.getenv() API.

- script: var dbPassword = $env("DB_PASSWORD");

$fail([message])

Fails the current test. If the message parameter is provided, it will appear in the stack trace, so you should always take the time to formulate a concise description that clearly explains the reason a test got failed, to make it easy for yourself and others to understand the root cause for the failure when looking at the test execution reports and/or logs.

- script: |
    if (person.name != "John Doe") {
        $fail(
            "We expected the name to be John Doe, " +
            "but we found " + person.name);
    }

$format(formatText, [formatItems])

Utility function for string formatting. Works similarly with String.format() in Java or printf() in C, except the placeholders are consecutive numbers between curly braces ({0}, {1}, etc.)

Example:

- script: |
    format("{0}, {1}!", "Hello", "world")   // "Hello, world!"

$image(relativePath)

Returns an image object of type BufferedImage. The argument is the relative path to the image in the "images" directory of the test repository. This function is intended to be used for supplying argument values for test actions that take image arguments.

$include(includeSource)

Includes (evaluates) one or more JavaScript file(s). The includeSource parameter can be either a string representing the path to the script file to include (relative to the scripts directory of the test repo), or an array of strings, in case you want to include multiple script files in one go.

Example 1 - including a single script file:

- script: |
    $include("moment.min.js");

Example 2 - including multiple script files:

- script: |
    $include(["moment.min.js", "lodash.core.min.js"]);

$json(objValue)

Converts the specified JavaScript value to a JSON string. This function is roughly equivalent with the JavaScript function JSON.stringify() and it’s the recommended way to serialize objects to JSON in OpenTest.

Example:

- description: Make an HTTP request with a JSON payload
  action: org.getopentest.actions.HttpRequest
  args:
    url: http://some.url.com
    verb: POST
    contentType: application/json
    body: |
      $json(
        {
          "prop1": "value1",
          "prop2": "value2"
        }
      )

$localData

An object that can be used to read and write data properties to/from the actor’s local data store. Properties written in the local data store are only readable by the test actor that created them. In other words, any other actors that are part of the same test will not be able to access each other’s local data. If you need to share data between test actors, see $sharedData and $sessionData instead. Internally, the local data store is just a Java HashMap managed by each test actor.

Example 1:

- script: |
    // Use the "$localData" object to write a value in the
    // local data store, under the property name "customer"
    $localData.customer = "John Doe";

    // Read the value of the "customer" property
    // and write it to the log
    $log("The customer name is " + $localData.customer);

$log(text)

Logs a line of text in the context of the current test session, at log level "informational". To log to other log levels, use the syntax $log.error(), $log.debug() and $log.trace().

Example:

$log("This is an informational message");
$log.error("This is an error message");

$macroArgs

An object that exposes all the arguments that were passed to a macro test action. This syntax is used inside of macro actions to read the values that were passed as arguments when the action was called.

Example:

test-repo-path/macros/SampleMacroAction
- description: |
    Display a greeting to the person specified in the "customerName" argument
  actions:
    - script: |
        $log("Hello, " + $macroArgs.customerName + "!");

$macroOutput

An object which can be used to write output values from a macro action. This is how a macro action can create output values that will be returned to the caller of the macro.

Example:

test-repo-path/macros/SampleMacroAction
- description: |
    Output a greeting text to the caller, under a
     property named "greeting"
  actions:
    - script: $macroOutput.greeting = "Hello there!"

$maskSecret(secretText)

Allows the test to declare a string that contains sensitive information and should not appear in the log file for the current test. After a call to the $maskSecret function, all the occurrences of the specified string in the log file will be replaces with a standard piece of text so as to mask that string. There is no limit to the number of strings that can be declared as secrets using this approach.

The $maskSecret function returns the exact string that was passed to it, so it can be used more easily when providing arguments to a test action (see example 2).

Example 1:

- script: $maskSecret("my-secret-password")

Example 2:

- description: Type the password in the login form
  action: org.getopentest.selenium.SendKeys
  args:
    locator: { id: password }
    text: $maskSecret("my-secret-password")

$output

An object that exposes the output values produced from a regular test action or macro action. This replaces the now deprecated $readOutput syntax.

The output values can be retrieved from this object using the standard JavaScript syntax - the dot operator or the subscript (square brackets) operator. For example, $output.text or $output["text"] returns the output value named text. Right after a test action executes, the $output object will be populated with all the output values that were generated by the test action that just finished executing.

Example:

- description: |
    Make ah HTTP request to get the HTML of the Google homepage and write the
    body of the response in the local data store, under the name "homepage"
  action: org.getopentest.actions.HttpRequest
  args:
    url: https://www.google.com/
    $localData:
      homepage: $output.body

- script: |
    $log("The Google homepage code was " + $localData.homepage));

$random(min, max)

Returns a random integer number between min and max.

Example:

$random(1, 100); // 87

$randomString(length, [characterPool])

Returns a random string with the specified length by randomly selecting characters from the character pool provided. If the character pool argument is missing, the default pool will be formed of all numbers and letters (both uppercase and lowercase).

Example:

$randomString(5);            // 2U8cM
$randomString(5, "ABC123");  // AB2AC

$readOutput(outputName)

Deprecated in favor of $output.

$runAction(actionName, args)

Runs a regular test action, with the specified arguments. This will produce the exact same effect as calling the action by using the regular YAML syntax, but has the advantage that can be incorporated into JavaScript code to cover more complex scenarios, when a test action must be executed in a loop or in a complex if…​else statement.

Example:

- script: |
    var hourOfDay = (new Date()).getHours();

    if (hourOfDay < 15) {
      $runAction("org.getopentest.actions.HttpRequest", {
        url: "http://restaurant.com/order/lunch"
      });
    } else {
      $runAction("org.getopentest.actions.HttpRequest", {
        url: "http://restaurant.com/order/dinner"
      });
    }

$runMacro(macroName, args)

Runs a macro action, with the specified arguments. The name of the macro has to include the path of the macro file, relative to the "macros" directory in the test repo. For example, if we have a macro file named "PrintMyName.yaml" located in the "macros/dir/subdir" directory, the syntax to call it would be:

- script: |
    $runMacro("dir.subdir.PrintMyName", {
      name: "John Doe"
    });

$sessionData

An object that can be used to read and write data properties to/from the session-scoped data store. Session data is stored on the sync server, which means that every time a test actor reads or writes to/from session data the actor makes an HTTP request to the sync server, which will have some impact on the execution time of the test. If the data doesn’t need to live all throughout a whole test session, you should be using the local or shared data stores instead (see $localData and $sharedData).

Note
Using session data is a bad practice, for the same reasons why using global variables is bad. Please avoid using this API, if you can help it - it is only provided to cover for those very few oddball use cases where there’s really no way around it.

Example:

- script: |
    // Use the "$sessionData" object  to write a value in the test
    // session's data store, under the property name "customer"
    $sessionData.customer = "John Doe";

    // Read the value of the "customer" property
    // and write it to the log
    $log("The customer name is " + $sharedData.customer);

$sharedData

An object that can be used to read and write data properties to/from the test-scoped ("shared") data store. Shared data is stored on the sync server, which means that every time a test actor reads or writes to/from the shared data store, the test actor must make an HTTP request to the sync server. Consequently, each $sharedData usage will add a few milliseconds to the execution time of the test. If a data property doesn’t need to be shared with other test actors, you should be using the local data store instead (see $localData).

Example:

- script: |
    // Use the "$sharedData" object to write a value in the
    // shared data store, under the property name "customer"
    $sharedData.customer = "John Doe";

    // Read the value of the "customer" property
    // and write it to the log
    $log("The customer name is " + $sharedData.customer);

$tempDir

A string variable that stores the full path to the actor’s temporary directory (e.g. C:\opentest\actor1\out\temp). Can be useful for building the full path of temporary files that might need to be created dynamically in a test.