Executing JavaScript
Run arbitrary JavaScript code in Momentic tests
Overview
Users can run arbitrary JavaScript code to craft complex logic and achieve dynamic behavior within steps. There are two places in which JavaScript can run:
JavaScript step
This is a special step that allows you to execute a block of JavaScript code. In the input field, you can write your own variables, functions, loops, etc. as if you were running code in a Node.js REPL. Asynchronous code (i.e. async
/ await
) is supported as well.
The output of the step is set to the final value return
ed by the code. This value must be serializable (e.g. you cannot return a class
or a function
). Two different execution contexts are available: Node.js and the browser.
{{ }}
expressions
Do not use {{}}
expressions within JavaScript steps. There is no need to do
so since any variables and functions can be referenced directly.
String fields in almost any step can contain JavaScript expressions inside curly brackets. At test runtime, these expressions are evaluated and the templated value is used instead.
For example, the value of a Type step can be set to {{ env.USERNAME }}@gmail.com
, which might evaluate to something like johndoe@gmail.com
.
You should not include a return
statement in these expressions. In addition, the expression inside the curly braces must fit on a single line. If you need multiple lines, use the JavaScript step instead.
Execution context
By default, all code executes in an isolated Node.js sandbox. This ensures that one test’s code cannot access other users’ data, modify the test environment, or consume excessive resources.
The JavaScript step also supports an option for executing the code in the current browser instead. This is useful for programatically interacting with the page. Since Momentic never reuses browser instances across tests, this option is equally as secure.
Globals
In addition to the Node.js built-in libraries, Momentic provides several third-party packages, special utility functions, and global constants to accelerate the testing experience.
These globals are only available in the Node.js sandbox environment. If you would like to use a library not listed below, please reach out to us for assistance.
Third-party packages
Special utility functions
Constants
Was this page helpful?