Selenium RC: How to click buttons that use onclick window.location?
Asked Answered
W

2

1

I have a button (outside of a form) that redirects to another page using the onclick attribute that calls window.location to redirect the user to another page. This time I can't change the HTML. I am using Safari 4 for testing. How can I click a button that uses the onclick attribute and window.location to redirect using Safari 4 and Selenium RC PHPUnit Extension?

Here's my HTML:

<input type="button" onclick="window.location='/registrations/new'" value="Start a new registration" id="create">

Update: Alternatively, I'm thinking about doing something where I assert that a location is specified in the window.location='', store that location, and call the open() command using that location. Not sure if this is an acceptable approach to testing this.

Winegrower answered 1/6, 2010 at 22:58 Comment(3)
What happens when you click it, the standard way?Lever
It works fine when you are clicking it manually. But it does not redirect when trying to click it with Selenium RC.Winegrower
What happens when you run the test in another browser? I've tested this successfully in Firefox, is this just an issue with Safari?Hannibal
W
2

We decided to extend the default clickAndWait() functionality to call openAndWait() if the button has an onclick="window.location='/something';"

/**
 * Extends original clickAndWait() functionality to provide the ability to click buttons that use window.location to redirect users
 * @param $locator
 */
public function clickAndWait($locator)
{
    $this->assertElementPresent($locator);
    $hasOnclickAttribute = $this->getEval('this.browserbot.findElement("' . $locator . '").hasAttribute("onclick")');
    if ($hasOnclickAttribute === 'true') {
        $onclickValue = $this->getAttribute("$locator@onclick");
        if (strpos($onclickValue, "window.location=") !== false) {

            // Clean up the location
            $temp = explode("=" , $onclickValue);               
            $location = trim($temp[1], "';");               
            $location = trim($location, '"');

            return $this->openAndWait($location);
        }
    }
    return parent::clickAndWait($locator);
}
Winegrower answered 2/6, 2010 at 16:41 Comment(0)
H
0

This should work, however you could also try firing the click event using the fireEvent command.

selenium.fireEvent("id=create", "click");
Hannibal answered 2/6, 2010 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.