Testing frames with your Selenium Test

humphreyhumphrey Posts: 4
edited October 2019 in Selenic

Testing web pages with frames can be tricky and selenium has built in API to help make this easier but it's important to understand the gotchas associated with it. Even with those APIs its good to follow some best practices to make the code easier to follow and maintain.

Its easiest to imagine frames on a web page as a tree where the parent for a frame is the closet ancestor which is a frame element. One gotcha is to remember that the html page is considered a frame itself by the selenium api. Lets take a look at the following html example

<html>
    <iframe id="child1"></iframe>
    <iframe id="child2">
        <iframe id="grandchild1"></iframe>
    <iframe>
</html>

Let's say you wanted to switch to "child1". The code to do that would look similar to this

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(frameToBeAvailableAndSwitchToIt(1));

In this case we pass the argument 1 to the method in order to switch to the first frame that was loaded. This is straight forward enough but now let's say you want to test content on frame "grandchild1". To do so you must first go back up the tree to the top html page and then traverse back down. The code would look similar to this

driver.switchTo().defaultContent();
wait.until(frameToBeAvailableAndSwitchToIt(2));
wait.until(frameToBeAvailableAndSwitchToIt(1));

From a readability stand point when ever switching to a new frame it's always best to switch back to the root frame by calling driver.switchTo().defaultContent(); and traversing back down the tree to the frame you want to test. This will avoid any confusion as to what frame you're on when trying to switch to a new frame. Using the Parasoft Recorder in conjunction with the Selenic IDE plugin will generate code that adheres to this methodology.

Sign In or Register to comment.