Using JavaScript steps in the Trainer

mabl can execute user-supplied JavaScript snippets inside of a trained test and optionally save the result as a variable. Both synchronous and asynchronous JavaScript code is supported. A number of user-created snippets can be found in our public JavaScript repo.

Generic Javascript Step

To insert a generic JavaScript step in the Trainer, click the "More actions" menu and then "Create JavaScript" to open the code editor.

Insert JavaScript step

Insert JavaScript step

A code editor window will open on the screen.

mabl Trainer Code Editor

mabl Trainer Code Editor

A predefined function called mablJavaScriptStep is supplied as the means of running the user-supplied JavaScript. This function has two arguments:

  • mablInputs:
    • a mabl supplied object containing read-only variables defined in the training session already.
mablInputs = {
  variables: {
    user: {
      // variables created during the trained journey thus far
      myCreatedVariable: "Variable value created earlier"
    }
  }
}
  • callback:
    • a mabl supplied callback function. This function should be called at the end to signify the completion of the JS snippet. Be sure to call this after the completion of any asynchronous code that needs to execute. Test execution will wait up to 30 seconds for the callback before failing. The callback must return a value.
    • Supported return types to the callback are:
      • boolean
      • string
      • number
    • Other types will cause a JS Step failure or be ignored

Enter your JavaScript code in the editor. When ready press the "Run" button and the entered JavaScript will be executed inside the console of the page you are on. If you got the desired result then press the Save button. You will then be presented with three options: "No Snippet", "New Snippet", and "Overwrite Existing Snippet".

Options for saving a JavaScript Snippet.

Options for saving a JavaScript Snippet.

Teamwork Opportunity

Saving a JavaScript step as a Snippet allows anyone in your workspace to use that step. With a descriptive snippet name and description, you will enable the rest of your team to understand what the step will do and easily reuse said step without them needing to understand the code.

Once the step is saved, you will see the JavaScript step show up in the trainer and you can continue creating your Journey.

Time saving tips

  • If you need to use the same JavaScript Step in multiple Journeys, make sure you save it as a Snippet. If later the JavaScript needs to be updated, you can update it in one place and all journeys will be updated.
  • The more reusable your code is, the better. Having a JavaScript Step that uses a variable that was set previously in the journey will allow for more code reuse. e.g. Picking a date from a date picker based off of the value of a variable named "date_to_pick". You would then set the variable "date_to_pick" and execute the JavaScript Snippet after to choose the desired date.

Adding saved JavaScript snippets to your journeys

Create a new journey from scratch or find and edit the journey in which you wish to add the snippet. Once in the trainer, navigate to the JavaScript icon and click, as shown in the screenshot above.

Select the "Load Snippet..." link and click. You'll see a list of your existing snippets, simply click the one you'd like to add. To finish, just click "Save" to save the journey itself.

Adding, editing, and managing your existing snippets in the snippets dashboard

Similar to reusable flows, you'll be able to see your saved JavaScript snippets on the "Snippets" tab of the "Journeys" page.

Creating new snippets

Click the "New Snippet" button to get started creating a JavaScript snippet right from the settings page.

You'll be taken to a panel in which you can name the snippet, edit the description, and add your code below. Add the code to the editor below, ensure there are no errors present, and save.

Important Info: Naming JavaScript Snippets

Using a previously used snippet name when creating a new snippet will automatically overwrite the previously created snippet of the same name. Be sure to double-check that the name is unique!

Your new JavaScript snippet will now appear on the "Snippets" tab and will be usable across any trained journey!

Editing existing snippets

You can edit your snippets straight from the "Snippets" tab. Just click on the name of the snippet to open up the editor.

Once you're done editing, just click the save button below. Your changes will instantly propagate to any journey where the snippet appears.

Managing existing snippets

You can only delete snippets that are not being used in your journeys. Once all instances of a snippet are deleted, you'll be able to click the red "Delete" button on the right.

Viewing errors and Console statements

Any errors or console statements will be viewable from the DevTools console for the page you are on.

Important information about JavaScript libraries

External JavaScript libraries cannot be imported as part of a JavaScript step in a trained journey.

Using JavaScript to define a variable

You can use Javascript snippets to define a variable in the mabl Trainer. A "JavaScript" option is available under the create variable form.

Create JavaScript Variable

Create JavaScript Variable

From here you can click the "Open code editor" button to launch the code editor. The editor functions just like it does from the "JS" button in the main trainer toolbar except upon clicking "Save & Run" the output will be saved as the variable. You will still be able to review the output before saving the create variable form and optionally reopen the editor to edit the JavaScript.

Examples

Public JavaScript Snippet Repo

A number of user-created JavaScript snippets can be found at our public repo. Take a look to start using them in your journeys.

Use your other variables

Below is an example of accessing variables you have defined in your test at an earlier step. This example uses a variable containing a path ('user/profile/settings') and builds a URL with the current document URL and returns the value in the callback to save it as a variable.

function mablJavaScriptStep(mablInputs, callback) {
  
  // pull a previously defined variable out of the built-in mablInputs
  // object to use in the javascript code
  let path = mablInputs.variables.user.myTestPath;
  
  // get the current URL of the document
  let currentURL = document.URL;
  
  // create a new URL combining both javascript variables
  let finalURL = `${currentURL}/${path}`;
  
  // perform the callback with the finalURL value to be saved as a variable
  callback(finalURL);
}

Create a Variable of the Current Date/Time

You can use the JavaScript editor to create a variable that is the current date and or time by using the code editor within the create variable form and the Date object. Please refer to the Date object documentation for other ways to produce the time format.

function mablJavaScriptStep(mablInputs, callback) {
  // create a new Date object
  let today = new Date();
  // get the string representation of the date and time
  let finalDateTime = today.toLocaleString();
  // perform the callback with the result
  callback(finalDateTime);
}

Assert an expected path in the URL

If you would like to verify that you ended up at the right path during a Journey, you can use the custom JavaScript step to verify the path like so. If the path does not match, the JavaScript step will fail and so will the Journey.

function mablJavaScriptStep(mablInputs, callback) {
  if (document.location.pathname === '/pricing') {
    callback('pricing path confirmed on page');
  } else {
    throw Error("incorrect path found on page: " + document.location.pathname);
  }
}

mabl API Step for Validating 2xx response code and API requests

If you want to validate a 2xx response code or make API calls, you can use the following JavaScript.

If you are an enterprise or trial customer, you have the ability to create and use mabl API Steps.

Check for a valid 2xx response code

Normally, it is not possible to validate for a 2xx response code outside of the default "Visit home page" journey. You can, however, use the JavaScript editor to validate the response code and return the code in the test output logs. The example below verifies a 2xx response code on the target URL (https://uinames.com/api/?ext).

function mablJavaScriptStep(mablInputs, callback) {
  // set the URL you want to test as the variable
  let url = 'https://uinames.com/api/?ext';
  // check for the status code while passing credentials to the target website
  fetch(url, {
   method: 'GET',
   credentials: 'include'
 }).then(apiResponse => {
    console.log(apiResponse);
    if (apiResponse.ok) {
      return callback(apiResponse.status);
    } else {
      throw Error(`Unexpected response code of ${apiResponse.status} when retrieving ${url}`);
    }
  });
}

Async API Request

Below is an example of how to make an asynchronous API request inside the JavaScript step using the fetch API. This example queries the uinames.com API for fake generated user data and pulls out a credit card number.

function mablJavaScriptStep(mablInputs, callback) {
  
  // define a javascript variable for the uinames.com API endpoint
  let url = 'https://uinames.com/api/?ext';
  
  // perform an asynchronous fetch against the API endpoint that returns JSON responses 
  fetch(url).then(apiResponse => {
    // extract the json value from the response
    return apiResponse.json();
  }).then(jsonResponse => {
    // extract the credit card number and perform callback
    callback(jsonResponse.credit_card.number);  // sample output: "2589-7385-9065-7232"
  });
}

Asynchronous Errors

Sometimes you will find yourself in an asynchronous callback function and need to throw an error all the way back to mabl.

For this case, you can use return callback(null, 'My Error Message'); which will return control all the way back out to mabl and is equivalent to throw Error('My Error Message');

Using JavaScript steps in the Trainer


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.