When creating a snippet for a browser or mobile test, the Snippet Editor starts with a predefined mablJavaScriptStep function. Understanding how to write your code within this predefined function is an important first step to implementing custom JavaScript in your tests.
This article describes the components of the Snippet Editor for browser and mobile tests, including examples to illustrate how they work:
- GenAI Script Generation
- The mablJavaScriptStep function
- Parameters
- The mablInputs object
- The callback
- Save options
- Version dropdown
Snippets in API tests work a bit differently. For more information on working with API snippets, check out this article.
GenAI Script Generation
If you're new to writing snippets or just need help getting started, try describing what you want to do in the AI Snippet Generator. Enter your prompt into the input field and click Generate to create a new snippet or modify an existing snippet.
See the article on GenAI Script Generation for more information.
The mablJavaScriptStep function
Every snippet consists of a predefined function called mablJavaScriptStep. Your code goes within this function.
External libraries
Importing external JavaScript libraries is currently not supported.
For example, the following snippet takes the value of the variable string, converts it to lowercase, and passes the output to the callback function:
function mablJavaScriptStep(mablInputs, callback) {
string = 'SAMPLE'
const result = string.toLowerCase();
callback(result);
}
By default, the mablJavaScriptStep function has two parameters: mablInputs and callback. If you want to pass in different input values for your snippet, you can also add custom parameters.
Parameters
To make a snippet more reusable in different contexts, add custom parameters to the left of the code editor:
The parameters section in the Snippet Editor
With parameters, you can access variables from the test, including test-generated, data-driven, and environment variables. To reference a variable, use mabl variable syntax: {{@var_name}}. Start typing {{@ to see which variables are available for the snippet.
For example, if you extracted a last name from the page and stored it in the variable last_name, you could reference the variable in your snippet with {{@last_name}}.
function mablJavaScriptStep(mablInputs, callback, string = `{{@last_name}}`) {
if (string === undefined) {
throw "parameter 'string' was not defined"
}
const result = string.toLowerCase();
callback(result);
}
To reuse the snippet in a different context, override the value of the parameter:
The Snippet Editor always passes parameter values as strings. For example, if you have a JSON response body returned from an API step and you pass it in as a parameter, it will become a string instead of an object.
When a parameterized snippet is inside a flow, any updates to the snippet parameter values automatically apply to all instances of the flow. If you want to scope parameter values locally to each instance of a flow, create flow parameters instead and use them as the snippet parameter values.
mablInputs
mablInputs is a read-only object containing variables available in the test. Previously, snippets did not support parameters, and the mablInputs object was the only way to access variables from the test.
Here are some examples of variables that you can access through the mablInputs object:
| Variable(s) |
mablInputs path |
|---|---|
|
Test-generated variables, data-driven variables, and environment variables |
mablInputs.variables.user.variable_name |
| The loop index | mablInputs.variables.web.runtime.flow_run_ordinal_index |
| The test run ID | mablInputs.variables.web.test_run_id |
| mabl credentials |
|
Unlike parameter values, which are always converted to strings, variable values accessed through mablInputs retain their original type. For example, if a variable's value is the response body from an API call, the variable will still be an object.
Callback
The callback function completes the snippet step. The value that the callback returns is rendered as output for the snippet step. After the callback runs, mabl proceeds to the next step in the test.
Maximum run time for a JavaScript snippet
All JavaScript steps are complete when the callback() is invoked. The maximum runtime for a snippet is five minutes, and it will fail if the callback() isn't called within that time.
If your snippet includes code that takes more than 5 minutes to run, you may try using the setTimeout() function. Since setTimeout() doesn't block the callback() from being invoked, you can schedule actions that execute after the JavaScript step is complete
Supported types of return to the snippet include:
- Booleans
- Strings
- Numbers
- Objects*
*For successful return values, only plain objects are supported. In failure scenarios, the callback may return an Error object to fail the step and provide logging. Other object types, including new Date() or custom class instances, are not supported as return values in the snippet callback.
If the callback function doesn't run or doesn't return a value, the snippet step will fail.
Asynchronous operations
Although the mablJavaScriptStep function requires a callback value to complete the step, it also supports other asynchronous operations, including async/await and promises.
Async/await and promises
Functions declared with asyncreturn a promise, and await pauses the execution of the function until the promise resolves.
For example, the following JavaScript snippet sets the geolocation for a mobile device with asynchronous functions. It makes an asynchronous call to callAppium() to access the Appium driver object and set the geolocation, and then it uses promises to return the result:
function mablJavaScriptStep(mablInputs, callback, altitude = "10", latitude = "48.85873;", longitude = "2.29373") {
async function callAppium() {
const driver = await mabl.mobile.getDriver();
await driver.setGeoLocation({ latitude, longitude, altitude });
return "Geo Location set: " + latitude + ", " + longitude + ", " + altitude;
}
callAppium()
.then((result) => callback(result))
.catch((error) => callback(error));
}
In this example, if the callAppium function returns a rejected Promise, the snippet returns an error object. Returning an error in the callback causes the step to fail and exposes error logs in the test results. If you don't want the snippet to fail the step, you can catch and handle the error within the script.
Save options
Click on the down arrow next to the Save button to see the full range of save options:
Save
The default option for existing snippets.
Save as one-time snippet
Saving as a one-time snippet can be useful if you have no plans of reusing the snippet. If you change your mind later, however, you can always convert a one-time snippet into a reusable snippet by clicking "Save as new reusable snippet."
One-time snippets do not appear on the snippets page and are versioned like any other test step.
Save as new reusable snippet
If you need to use the same JavaScript step in multiple tests or several times in the same test, save it as a reusable snippet. If the JavaScript needs to be updated later, you can update it in one place. All tests that contain the snippet will use the updated version.
Snippets and branching
Reusable snippets do not adhere to branching. Any changes made to a reusable snippet will synchronize across all usages of it. To manage a snippet on a branch, save it as a one-time snippet and put it in a reusable flow.
All snippets that appear on the snippets page - Tests > Snippets - are reusable snippets. When working with snippets from the snippets page, keep in mind the following:
- New snippets are always saved as reusable snippets.
- While existing snippets can be updated, you cannot create a new snippet from an existing snippet outside of the mabl Trainer.
- If you want to check the results of a snippet for a browser or mobile test, you need to open the snippet in the mabl Trainer.
Version dropdown
Every time you save changes to a snippet, mabl creates a new version. Use the version dropdown to track changes to snippets and restore older versions.
Accessing older versions of a snippet
Snippet change history is only accessible for snippets edited from the snippets page: Tests > Snippets.
Although saving a snippet from within the mabl Trainer does create a new snippet version, the Snippet Editor in the mabl Trainer does not include a version dropdown.