Replace a String
Use the following code replacing a version number in a message as an example of string replacement using CloudTest > Scripts. This script example represents the output of a recorded clip for HTTP traffic. These messages have strings in them that contain the CloudTest build version number. In order to make the clips portable across versions, it is necessary to either replace the version with a generic version string ("version") or the real new version number.
Refer to Script to learn how to add a script to a test clip and test composition.
- Specify the last build number as
var versionToReplace = "version20";
- Set a variable,
version, with its value as "version".
var version= "version";
Create an array,
clipElements, and populate it with the children of the
currentClip. Cycle through all the elements.
- Line 4 returns the var (clearly an array) which points to the children. Line 5 creates the "for" loop to cycle through those array elements.
var clipElements = $context.currentClip.children; for (var i=0; i<clipElements.length; ++i)
- Get the next item in the clip.
var clipElement = clipElements[i]; if (clipElement.type == "Message")
- For each clip element whose type is "Message", its version is updated to the new version.
What you should see
origMessageis the original message body and
newMessageis the newly constructed replacement message body (with the build number replaced), which is then put back into the message.
If there was something in the message text that was replaced (causing
to not equal
), then use
to put the changed message back into the message. The remaining lines of code post text stating that the replacement has been done.
var = clipElement.getMessage(clipElement.MESSAGE_HTTP_BODY);
var newMessage = origMessage.replace(
if (origMessage != newMessage)
$context.result.postMessage($context.result.LEVEL_INFO, "Replaced version string in Message.", "Original Message: " + origMessage + "\n\nNew Message:
" + newMessage);