Using Javascript for Writing Expressions– Source Reference
JavaScript can be used to write an expression to select and to manipulate data items.
An expression can be used with the replaceable Expression element where the result of the expression is used as a value in the test scenario. It can be used with the Verify element to express actual and expected values, it can be used in the expected value and verify expression attributes on a data item in a component execution, and finally it can be used to set a data value by starting the value with a = (equal) sign. The possibilities specific for each element type are described in details in the sections below.
Common for expressions are that they can access all data from previously executed Referenceable elements, for instance results from SQL Select statements and component executions. Non-virtualized Test automatically converts the data items to JSON objects before executing an expression. Using JSON in expressions makes it easy to manipulate the data. The expression must return a string, a boolean, a number, or a JSON object. The returned data is automatically converted to Non-virtualized Test data items.
For instance, let’s assume we have a Variable element as illustrated above.
The corresponding expression for selecting the data item /A[1]/B[0]/* would be
Expressions do not support the wildcard or the // tricks in the data path in previous section. Instead plain JavaScript must be written.
Using expressions based on JavaScript in a Total Test Scenario gives a high degree of flexibility as many complex operations can easily be implemented.
Expressions can be simple statements like anId.toUpperCase() and anId.substring(3,5)+’xyz’, or more complex statements with declaration and use of operations.
A valuable feature when writing complex statements is the possibility to use the println(<message>) method. This method will write the <message> to the execution log and is valuable when constructing and debugging a statement.
The example below shows an example of an expression that calculates the sum of 1+2+3+4+5+6+7+8+9+10 using an array and a recursive function and writes it to the console using the Log element.
The execution log for this example is shown below.
<data:String>Value:</data:String>
<data:Replaceable>
<Expression>
<Statement><![CDATA[var values = [1,2,3,4,5,6,7,8,9];
function sum(array){
println('array length:'+array.length);
if(array.length==1){return array[0]}
return array[0] + sum(array.slice(1, array.length));
}
sum(values);]]></Statement>
</Expression>
</data:Replaceable>
</Log>