Embedding Test Scripts Into Web Pages

Applies to: TestComplete 8-10

TestComplete Web Module includes rich functionality that helps you create functional web tests. You can easily simulate keystrokes and mouse clicks on buttons, text boxes and other controls and elements of your web pages. TestComplete’s test engine also has access to methods and properties of web page elements, so you can easily check the attributes and contents of tested web elements.

However, there are some cases when you may need to embed some script code into a web page while running your test on the page. Being embedded into the page, the script code can perform actions that are difficult to perform from tests running in TestComplete. Here are some examples:

  • Your page may contain script code with global variable definitions. The browser script engine does not provide TestComplete with access to them. To check or set these variables’ values from your test, you can embed script code into your page. This code will get access to the global variable for reading or for both reading and writing. You can call the embedded functions from your TestComplete test to obtain variable values or assign new values to them.
  • You may need to verify that your page’s elements behave in a certain way after some actions on them have been performed. For this purpose, you can embed event handler code into your page and then assign event handlers for the needed elements directly from TestComplete.
  • Also, you can use TestComplete to create custom scripts checking whether some objects (for example, a progress bar) were shown on the screen during a test. This can be really useful if you need to test an object visible on the screen within a very short period of time.

In the cases described above, as well as in any other case requiring that you create custom scripts that will run on the tested web page, TestComplete lets you create and add such scripts (embed them) to the tested page directly from your tests.

Note that all embedded scripts are saved within the tested page’s code until you refresh the page. When the browser refreshes the page, it updates the page’s contents, and all the objects added to the page dynamically are lost.

General Procedure

To embed the needed code to the tested web page, follow the instructions below:

  1. First of all, from your test, you need to get access to the page’s contents (the body element). For this purpose, add the following code to your test (the sample code is written in the JScript language):

    // TestComplete JScript code
    // This code accesses the “body” element of the page
    // shown in the Internet Explorer browser

    // Access the Page object
    var Proc = Sys.Process("btIExplorer");
    var Page = Proc.Page("http://www.mysite.com/Test.html");
    // Access the document element
    var Document = Page.Application.document;
    // Access the body element
    var Body = Document.body;

  2. After that, you need to create a script element that will be embedded into the web page directly from your test:

    // TestComplete JScript code

    // Create a script element
    var script = Document.CreateElement("script");

    // Specify the type of the script

    script.setAttribute('type', 'text/javascript');

    // Specify the script to be embedded into the page
    // This code will run in the web page

    script.text = "function MyFunc()"+

        +"{ /* The body of the function */ }" +

        +"MyFunc();";

  3. Now, we are ready to include the created element (script) in the hierarchy of custom objects on the web page (let’s add it to the end of the page’s HTML code, for example). For this purpose, add the following code to the test:

    // TestComplete JScript code

    // Specify the insertion point for the script

    script = Body.InsertBefore(script, null);

  4. After the code is embedded into the web page, you can easily call it from your test. For example, you can do this by adding the following lines to your test:

    // TestComplete JScript code

    // Call the embedded script – the MyFunc() function
    var Res = Document.Script.MyFunc();

    // Post the function’s result (if any) to the test log

    Log.Message(Res);

  5. So, to embed JScript code to the web page directly from your test, open this page (in our example, it is http://www.mysite.com/Test.html) in Internet Explorer and then run the created Main() routine (see the code below) from TestComplete:

    // TestComplete JScript code

    function EmbedCode()

    {

      // Access the Page object

      var Proc = Sys.Process("btIExplorer");

      var Page = Proc.Page("http://www.mysite.com/Test.html");

      // Access the document element

      var Document = Page.Application.document;

      // Access the body element

      var Body = Document.body;


      // Create a script element

      var script = Document.CreateElement("script");


      // Specify the type of the script

      script.setAttribute('type', 'text/javascript');


      // Specify the script to be embedded into the page

      // This code will run in the web page

      script.text = "function MyFunc()"+

          +"{ /* The body of the function */ }" +

          +"MyFunc();";

      // Specify the insertion point for the script

      script = Body.InsertBefore(script, null);

    }

    function Main()

    {

      // Embed the code into the web page

      EmbedCode();


      // Call the embedded script – the MyFunc() function

      var Res = Document.Script.MyFunc();

      // Post the function’s result (if any) to the test log

      Log.Message(Res);

    }

    The specified code (in our example, it is the MyFunc() routine) will be automatically embedded into the web page, TestComplete will run this function and then post its result (if any) to the test log.

    However, sometimes, you may need to run the embedded script after an event has happened or if some conditions are met. In this case, you can call the MyFunc()routine from the handler of the target event (see below).

We would like to note again that all the embedded scripts work until you refresh the web page. This behavior is conditioned by the fact that the browser updates the page contents when refreshing the page, so all the elements that were dynamically added to the page are destroyed irreversibly.

Getting and Setting Values of the Script’s Global Variables

Sometimes, you may need to check whether your page can work with different values of the script’s global variables. For this purpose, you can access these variables from the script that will be added to the tested page. Suppose that you test a web page that uses the My_var1 global variable. To obtain the value of this variable in your test, you can embed the following script to the tested web page and then call this code from your TestComplete test:

// JavaScript code that will be embedded and run in the web page

function GetGlobalVar()

{

  // Shows a message containing the variable value

  return My_var1;

}

// Runs the function

GetGlobalVar();

To embed this script to the page, create the following test (JScript unit) in TestComplete:

// TestComplete JScript code

function EmbedCodeForGlobalVar()

{

  // Access the Page object

  var Proc = Sys.Process("btIExplorer");

  var Page = Proc.Page("http://www.mysite.com/Test.html");

  // Access the document element

  var Document = Page.Application.document;

  // Access the body element

  var Body = Document.body;


  // Add a JScript element to the page

  var script = Document.CreateElement("script");

  script.setAttribute('type', 'text/javascript');

  // Specify the script to be embedded

  // This JScript code will run in the web page

  script.text = "function GetGlobalVar ()" +

      +"{return My_var1;}" +

      +"GetGlobalVar();";


  // Specify the insertion point for the script

  script = Body.InsertBefore(script, null);

}

function Main()

{

  // Embed the script into the page

  EmbedCodeForGlobalVar();


  // Call the embedded script – the GetGlobalVar() function

  var Res = Document.Script.GetGlobalVar();

  // Post the value of the global variable to the test log

  Log.Message(Res);

}

Now, open the tested web page in Internet Explorer and run the Main() routine (see the code above) from TestComplete. As you can see, this routine calls the EmbedCodeForGlobalVar() function. This function gets access to the tested page’s contents and then embeds the GetGlobalVar () routine into the web page:

// TestComplete JScript code

function EmbedCodeForGlobalVar()

{

  // Access the Page object

  var Proc = Sys.Process("btIExplorer");

  var Page = Proc.Page("http://www.mysite.com/Test.html");

  // Access the document element

  var Document = Page.Application.document;

  // Access the body element

  var Body = Document.body;


  // Add a JScript element to the page

  var script = Document.CreateElement("script");

  script.setAttribute('type', 'text/javascript');

  // Specify the script to be embedded

  // This JScript code will run in the web page

  script.text = "function GetGlobalVar ()"+

      +"{return My_var1;}" +

      +"GetGlobalVar();";


  // Specify the insertion point for the script

  script = Body.InsertBefore(script, null);

}

Using the approach described above, you can also set new values for the script’s global variables. You can do this via embedding the following script into the page:

// JavaScript code that will be embedded and run in the web page

function SetGlobalVar()

{

  // Assign a new value to the global variable defined in the page

  My_var1 = "New_value";

}

// Run the function

SetGlobalVar();

Embedding Event Handlers into Web Pages

Suppose that your tested page contains the following input element:

<input type="button" name="MyButton" value="Submit"></input>

Now, we will create a handler for the button’s oncontextmenu event (this event occurs when you right-click the specified button). As it was mentioned above, such custom handlers help you run embedded scripts after an event has occurred, for example, after a button was right-clicked. It may be very helpful if you embed script code that verifies validity of the data submitted to the server. So, you can run the embedded code every time a user clicks the Submit button and data is sent to the server.

To create the event handler and embed it into the web page, we will use the attachEvent method of the HTML document. For example, right-clicking the button may call the MyFunc() function that performs the following actions:

// JavaScript code that will be embedded and run in the web page

function MyFunc()

{

  alert("The button was right-clicked.");

}

To embed the code specified above to the web page, we will use the following function:

// TestComplete JScript code

function EmbedEventHandler()

{

  // Access the Page object

  var Proc = Sys.Process("btIExplorer");

  var Page = Proc.Page("http://www.mysite.com/Test.html");

  // Access the document element

  var Document = Page.Application.document;

  // Accesses the body element

  var Body = Document.body;

  // Add the JScript element to the page

  var script = Document.CreateElement("script");

  script.setAttribute('type', 'text/javascript');

  // Specify the script to be embedded

  // This JScript code will run in the web page

  script.text = "function MyFunc(){alert(""The button was right-clicked"");}";

  // Insert the script at the end of the body element

  script = Body.InsertBefore(script, null);

}

To “bind” the embedded function to the specified event’s handler, we must attach the event to the button and then specify the embedded routine as code for the event handler. For this purpose, we will use the following function:

// TestComplete JScript code

function AttachEventHandler()

{

  // Access the button element

  var MyBut = Page.Panel(0).Button("MyButton");


  // Attach the oncontextmenu event to the button

  Document.Script.execScript("MyBut.attachEvent('oncontextmenu', MyFunc);");

}

Now, let’s make sure that the created scripts work correctly. For this purpose, let’s open the tested web page in Internet Explorer and then run the following routine:

function Main()

{

  // Embed the code into the web page

  EmbedEventHandler();


  // Attach the embedded code to the event handler

  AttachEventHandler();

}

For this purpose, right-click the Main() routine’s code in TestComplete and select Run Current Routine from the ensuing context menu.

After the test is launched, you can click the button (to which the specified event handler has been added) on the page, and a message informing you about the click will appear.

Full Code of the Sample

Embedding Custom Scripts for Other Purposes

Sometimes, you may need to check whether your application performs certain actions that have no visual effect. For example, you may need to make sure that your application sends the correct data to the server, or you may need to check whether an object staying on the screen for a very short period of time was shown on the screen (for example, a progress bar or loading window). Typically, it’s difficult for TestComplete to recognize such objects and catch their appearance as it may refresh information after the object has already disappeared. To solve such problems, you can create a custom script, embed it to the tested web page and then use this script to verify whether the expected object was shown.

For this purpose, you can create a custom handler for the event that you need to test (an object’s appearing, sending data to the server, and so on) and make the handler perform some actions if the needed event is fired. For example, every time the event is fired, TestComplete can create a hidden element on the web page. So, while running your test, you just need to verify whether the specified hidden element is on the web page. This feature may assist you in creating more comprehensive tests for your web pages.

For example, we will create a script that will check whether the Loading window has been shown on the screen. As you may know, when this window is shown, the onload event occurs. So, we will create a handler for this event. The handler will create a hidden element on the page every time the event occurs. So, to verify whether the Loading window has appeared, we just need to check whether the specified hidden element is on the page.

For the approach described above, we will create several functions that will embed the code for the event handler into the web page, attach this code to the event and then check whether the hidden element was created by the handler.

The embedded script will look like this:

// JavaScript code that will be embedded and run in the web page

function HiddenElement()

{

  // Create a new input element on the page

  var hidElem = document.CreateElement("input");


  // Specify the attributes for the created element

  hidElem.setAttribute('name', 'hiddenElement');

  hidElem.setAttribute('aria-hidden', 'true');

}

To embed this code to the page, we will use the following TestComplete code:

// TestComplete JScript code

function EmbedCode()

{

  // Access the Page object

  var Proc = Sys.Process("btIExplorer");

  var Page = Proc.Page("http://www.mysite.com/Test.html");

  // Access the document element

  var Document = Page.Application.document;

  // Access the body element

  var Body = Document.body;


  // Add the JScript element to the page

  var script = Document.CreateElement("script");

  script.setAttribute('type', 'text/javascript');


  // Specify the JScript code to be embedded


  // This JScript code will run in the web page

  // and will create a hidden element on the page

  // if the onload event occurs

  script.text = "function HiddenElement(){var hidElem ="+

      +"document.CreateElement("input");"+

      +"hidElem.setAttribute('name', 'hiddenElement');"+

      +"hidElem.setAttribute('aria-hidden', 'true');}";


  // Insert the script at the end of the body element

  script = Body.InsertBefore(script, null);

}

To attach the embedded script to the onload event’s handler, we will use the function below:

// TestComplete JScript code

function AttachEventHandler()

{

  // Access the specified Loading Window object

  // that presents a table in our example

  var LoadingWindow = Page.Panel(0).Table("Loading_Window")

  // Attach the onload event to the Loading window

  Document.Script.execScript("LoadingWindow.attachEvent('onload', HiddenElement);");

}

After that, the test will perform some actions over the tested page and then check whether the hidden element is on the page. The entire code for the approach described above looks like this:

// TestComplete JScript code

function EmbedCode()

{

  // Access the Page object

  var Proc = Sys.Process("btIExplorer");

  var Page = Proc.Page("http://www.mysite.com/Test.html");

  // Access the document element

  var Document = Page.Application.document;

  // Access the body element

  var Body = Document.body;


  // Add the JScript element to the page

  var script = Document.CreateElement("script");

  script.setAttribute('type', 'text/javascript');


  // Specify the JScript code to be embedded


  // This JScript code will run in the web page

  // and will create a hidden element on the page

  // if the onload event occurs

  script.text = "function HiddenElement(){var hidElem = document.CreateElement("input");"+

      +"hidElem.setAttribute('name', 'hiddenElement');"+

      +"hidElem.setAttribute('aria-hidden', 'true');}";


  // Insert the script at the end of the body element

  script = Body.InsertBefore(script, null);

}

function AttachEventHandler()

{

  // Access the specified Loading Window object

  // that presents a table in our example

  var LoadingWindow = Page.Panel(0).Table("Loading_Window");

  // Attach the onload event to the Loading window

  Document.Script.execScript("LoadingWindow.attachEvent('onload', HiddenElement);");

}

function Main()

{

  // Embed the script code into the web page

  EmbedCode();


  // Attach the embedded code to the event handler

  AttachEventHandler();


  // Actions that may cause the Loading window to appear

  // …


  // Check whether the Loading window has been shown

  // In other words, it checks whether the hidden element exists

  if (Document.hiddenElement.Exists())

    Log.Message("The Loading window has been shown.")

  else

    Log.Message("The Loading window hasn’t been shown.");

}

To try the approach described above, open the tested web page in Internet Explorer, copy the script above to TestComplete and run the Main() function.

Conclusion

We hope, this article contains information that will help you create more powerful and reliable web tests with TestComplete. If you already have TestComplete installed, make sure that you have downloaded the latest version of TestComplete from My SmartBear section of our web site (https://my.smartbear.com). If you haven’t used TestComplete yet, download and try it for free.