Share this page

# Work with JavaScript

This topic contains tips for coding in JavaScript in your TruClient 2.0 - Web scripts.

In this topic:

## JavaScript support

JavaScript is supported in three areas. The JavaScript expressions are evaluated during script replay:

- Arguments. The values in the Arguments section of each step can be JavaScript-based, and accept JavaScript expressions.

- Descriptors ID method. The Value and Object ordinal fields for the descriptors accept JavaScript expressions.

- JavaScript ID method. Accepts JavaScript expressions.

Back to top

## JavaScript execution context

There are two JavaScript execution contexts in TruClient for the application under test (AUT):

- Default context. The default JavaScript context is outside of the AUT browser. The JavaScript code for the step arguments, and for the descriptors ID method, runs in this sandbox context.

- AUT context. This JavaScript context is inside the AUT browser. It is used to access JavaScript objects and functions in the AUT, such as the window object or document object, as well as the whole DOM tree. The JavaScript code for the JavaScript ID method runs in this context.

  AUT context is exposed as the AUT variable, which uses the evaluate() method to evaluate the JavaScript code.

  Note: Predefined JavaScript API variables are not available in the AUT Context.

Example:

In the following example, the overall JavaScript code runs in the default context, while the function argument of AUT.evaluate() method runs in the AUT context.

The variable id is passed from the default context to the AUT context, while the tagName of the element is returned from the AUT context to the default context.

Copy code

    (async () => {
            const id = ‘#myid’;
            const tag = await AUT.evaluate((id) => {
                const element = document.querySelector(id);
                if (element) {
                    return element.tagName;
                }
            }, id);
    })()

Back to top

## JavaScript variables

Predefined JavaScript variables are provided for the default and AUT contexts. You can also define new variables. The accessibility of variables is determined by their scope.

Default context variables

The following table describes variables in the default context:

Variables | Usage | Scope
--- | --- | ---
Global (predefined) | Add variables to the predefined Global variable, using this format: `Global.myVariable = ‘myVariableValue’;` | The defined variables have global scope, meaning they exist during the entire script replay. They can be accessed by any step, in any iteration. For details, see Global variables and functions.
Iteration (predefined) | Add variables to the predefined Iteration variable, using this format: `Iteration.myVariable = ‘myVariableValue’;` | The defined variables have iteration scope, meaning they can be accessed by steps in the current iteration only. The value of the variables is cleared when a new iteration starts.
JavaScript API (predefined) | Add predefined TruClient JavaScript API variables containing predefined functions. These include: TC Utils IO | N/A
<User defined> | Add new local-scope JavaScript variables, using the let keyword: `let myVariable = ‘myVariableValue’;` Note: Do not use the var keyword. | The defined variables are within the local/step scope, meaning they can be accessed in the current code block only. Use local scope whenever possible, to avoid polluting iteration or global scope.

AUT context variable

The AUT context has one predefined variable: Object, in the Evaluate JavaScript on object step.

The object variable represents the step’s test object in the AUT.

Example:

This code triggers a click action on a clickable DOM element, such as a button.

    AUT.evaluate(()=>{
        object.click();
    });

Back to top

## Global variables and functions

The predefined Global variable represents the global scope in the default context. To define global variables and functions, you add them to the Global variable.

You can define global variables and functions in an Evaluate JavaScript step in the Init action.

Note: You can also define global variables and functions in the JS-functions.js file in the script folder, but this should be avoided. Libraries are now used for custom code, although the JS-functions.js file is still supported for backward compatibility.

Global variable format:

Copy code

    Global.myVariable = ‘myVariableValue’;

Global synchronous function format:

Copy code

    Global.mySyncFunc = (a, b) => {
        return a + b;
    }

Global asynchronous function format:

Copy code

    Global.myAsyncFunc = async (name) => {
        return await TC.getParam(name);
    }

Access global variables and functions

Global variables and functions are accessible in default context across iterations.

For example:

Copy code

    (async ()=>{
        await TC.setParam('paramName', 'paramValue');
        await TC.log(Global.myVariable);
        await TC.log(Global.mySyncFunc(1,3));
        await TC.log(await Global.myAsyncFunc('param'));
    })();

Back to top

## Work with asynchronous JavaScript code

APIs provided by modern browsers are asynchronous. To align with this, TruClient provides asynchronous JavaScript APIs, exposed by the TC, Utils, and IO variables.

As asynchronous functions, the JavaScript APIs return a promise. The recommended way to work with a promise is using async/await keywords. The await keyword cannot be used for top level code, so it must be wrapped inside an async function.

For example:

Copy code

    (async () => {
        return await TC.getParam(‘param’);
    })();

Writing and running single-line asynchronous JavaScript code like this can be cumbersome. To simplify it, when the return value of a code block is a promise, TruClient waits for the promise to be resolved or rejected. The function uses the resolved value or rejected error as the result.

With this support, the above example code can be simplified to:

`TC.getParam(‘param’);`

For details on the available API functions, see TruClient 2.0 - Web functions in the VuGen Function Reference.

Back to top

## Custom code snippets

In addition to the built-in JavaScript code snippets, you can create your own custom code snippets for reusable blocks of code. When editing JavaScript code, for example, in an Evaluate JavaScript step, you can use the snippets to speed up the coding process.

To use snippets in the JavaScript code:

1. Open the General settings > Code snippets tab.

2. Click Add a new code snippet . A new code snippet template is opened, using a default label.

3. Edit the snippet Label, and define Documentation to describe its purpose.

   The label is used to access the snippet in the JavaScript editor.

4. Click Save in the General settings dialog box.

5. When creating or editing an argument for a step in the JavaScript editor, start typing the label for the snippet. Select the snippet from the auto-suggest list, to add the snippet content to the code.

Back to top

See also:

- Event handlers
- Steps box

https://admhelp.microfocus.com VuGen,Professional Performance Engineering,Performance Engineering for Developers 8942
Tips to improve your search results... OpenText™ Virtual User Generator Help Center OpenText™ VuGen Help 25.1-25.3 All View Local Help Center View Online Help Center Version: