简体   繁体   中英

Selenium click doesn't work with angularjs ng-click event

I'm looking to verify a particular external function is called on a ng-click event. The input declaration is as follows. This works fine in the browsers, so there are no problems functionally, only during testing with Selenium I'm not seeing the correct result. myFunction is calling an external myExternalFunction, which is the behaviour I'm trying to validate. We already have jasmine tests with spies validating this behaviour in a different environment, but Selenium is needed anyways. Also we don't use protractor at the moment. I'm looking for a solution with Selenium.

<input class="myClass" ng-click="myFunction()">

In the C# Selenium tests, I'm writing:

// Creating the mock external function since the context doesn't have it.
IJavaScriptExecutor executor = WebDriver as IJavaScriptExecutor;
executor.ExecuteScript("window.called='false'");
executor.ExecuteScript("window.external = {}");

// The behavior will be just setting the called variable to true.
// We will retrieve the variable and check the value to see if the function was called.
executor.ExecuteScript("window.external.myExternalFunction = function() {window.called = 'true';}");

// Select the element - there's only one element with this classname
IWebElement element = WebDriver.FindElement(By.ClassName("myClass"));
string value = "";  
// Verified via debugging that the element is actually valid.
// Tried the following options.

// 1) Just click and wait for event propagation - didn't work.
element.Click(); // Didn't do anything so added a Thread Sleep to make sure.
Thread.Sleep(1000);
value = WebDriver.ExecuteJavaScript<string>("return window.called;"); // returns false - expected to be true.

// 2) Use the actions to focus and click.
IWebDriver driver = WebDriver;
Actions a = new Actions(driver);    
a.MoveToElement(element).Perform();
a.MoveToElement(element).Click().Perform();
Thread.Sleep(1000);
value = WebDriver.ExecuteJavaScript<string>("return window.called;"); // returns false - expected to be true.

// 3) Select and click via javascript instead.
executor.ExecuteScript("angular.element('.myClass').click();");
Thread.Sleep(1000);
value = WebDriver.ExecuteJavaScript<string>("return window.called;"); // returns false - expected to be true.

I'm pretty much out of ideas at this stage. Is there no way to make Selenium play nice with angularjs? Similar question here: Selenium click event does not trigger angularjs ng-click without conclusive answer.

I would suggest, use xpath for locating the element and you should be good. Please share the xpath, if possible.

你可以使用css选择器,它应该工作:

By.cssSelector("input[ng-click='myFunction()']") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM