Execute JavaScript
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 our Set 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 from the Set Variable
action.
And you can also 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 the
Execute JavaScript
action to click on elements or to 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 that it might not behave in the same way in all browsers and you might need to adapt it.
For example, if you want your JavaScript code to run correctly in Firefox, you must usewindow.
before each variable. - If the execution of the JavaScript will throw any errors, you will see them in the output of that step.
External JavaScript Libraries
You can also import an external JavaScript library in an Execute JavaScript
step.
For example, this is how you would import the Chance.js
library:
s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://chancejs.com/chance.min.js";
document.getElementsByTagName("head")[0].appendChild(s);
And this is how you would call the phone()
method from that library:
phone = chance.phone();
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.
As mentioned at the beginning of this chapter, you can transfer a value from a JavaScript variable to an Endtest variable by using a Transfer to JavaScript
step.