ExecuteAutomation

Executing Javascript on Browser with Coded UI

In this post we will discuss one of the most useful and important feature of Coded UI testing, which is executing Javascript (or any script for that matter) on a browser using Coded UI. There are various advantages and uses of running a Javascript on the browser, since JS gives us the leverage of getting the complete DOM (Document Object Model) of the page and perform operations which the in-built methods of Coded UI test cannot perform (or can perform with lots of code)

Running Javascript with Coded UI

Using BrowserWindow’s ExecuteScript method we can execute any script on the browser, and we are going to execute a Javascript using the ExecuteScript() method. For example, to get the number of Html input controls on the given page, we can use the length method of getElementsByTagName() of javascript and get the value, here is the screenshot below for our login page

We can achieve the same result with coded UI as well with the help of FindMatchingControls() method and UITestControlCollection class as discussed in previous post but as we know, its lot of code and its slow comparing to Javascript. Here is the complete video explaining the above discussion Here is the code to execute a simple alert window of Javascript
        public BrowserWindow TopParentWindow()
        {

            //BrowserWindow.ClearCookies();
            //BrowserWindow.ClearCache();
            BrowserWindow window = BrowserWindow.Locate("Execute Automation");
            window.SearchProperties[UITestControl.PropertyNames.ClassName] = BrowserWindow.CurrentBrowser.ToString();
            Image image = window.CaptureImage();
            image.Save(@"D:\captured.jpeg", ImageFormat.Jpeg);
            image.Dispose(); 
            window.ExecuteScript("alert('Hello World')");
        }
Code to Get the total number of controls and check if they are correct
public BrowserWindow TopParentWindow()
{

    //BrowserWindow.ClearCookies();
    //BrowserWindow.ClearCache();
    BrowserWindow window = BrowserWindow.Locate("Execute Automation");
    window.SearchProperties[UITestControl.PropertyNames.ClassName] = BrowserWindow.CurrentBrowser.ToString();
    Image image = window.CaptureImage();
    image.Save(@"D:\captured.jpeg", ImageFormat.Jpeg);
    image.Dispose();

    //Execute Script to count the number of controls
    var result = window.ExecuteScript("var controlCount = document.getElementsByTagName('Input').length; return controlCount;");

    if (result.ToString() == "3")
        Console.WriteLine("PASSED");
    else
        Console.WriteLine("FAILED");

    return window;
}

Thanks for watching the video and reading the post !!! Please leave your comments and let me know if there is anything need to be improved in the post. Thanks, Karthik KK