Introduction
There are certain scenarios where you might need to execute some JavaScript code. For example, let’s say you want to generate a complex random pattern that you cannot obtain by using ourSet Variable
action and by concatenating variables and strings.
You can execute JavaScript code in your Web Tests by using an Execute JavaScript
step.
The JavaScript variables and the Endtest variables are on different layers, but you can exchange values between them:
- You can transfer a value from a JavaScript variable to an Endtest variable by using the
Extract Value from JS variable
option in theSet Variable
action. - You can transfer a value from an Endtest variable to a JavaScript variable by using the
Transfer to JavaScript
action.
You can find more details about the
Set Variable
action and variable concatenation in the Variables chapter. Steps
- Add an
Execute JavaScript
step. - Write your JavaScript code in our JavaScript editor.
- Save the test.
- Execute the test.
Mandatory Guidelines
- Do not use the
var
,let
, orconst
keywords when declaring variables and constants in your JavaScript code. - Do not add comments in your JavaScript code.
- Test your JavaScript code in your own browser console to make sure that it works as expected.
- Avoid using
Execute JavaScript
to click elements or write text in inputs.- Using JavaScript to perform such actions does not mimic a real user and your web application might behave differently.
- The JavaScript code is executed by the specific WebDriver for each browser.
- This means it might not behave the same way in all browsers, and you might need to adapt it.
- For example, if you want your code to run correctly in Firefox, you must use
window.
before each variable.
- If the execution of the JavaScript throws any errors, you will see them in the output of that step.
External JavaScript Libraries
You can also import an external JavaScript library in anExecute JavaScript
step.
For example, here’s how you might import the Chance.js
library:
phone()
method from that library:
The methods from the imported JavaScript library cannot be called from the same
Execute JavaScript
step. A new Execute JavaScript
step should be added for that. Transfer to JavaScript
step.