Selenium click不适用于angularjs ng-click事件

时间:2016-01-11 19:04:54

标签: javascript c# angularjs selenium selenium-webdriver

我希望验证在ng-click事件上调用特定的外部函数。输入声明如下。这在浏览器中工作正常,因此在功能上没有问题,只有在使用Selenium测试期间我没有看到正确的结果。 myFunction正在调用外部myExternalFunction,这是我尝试验证的行为。我们已经进行了茉莉花测试,间谍在不同的环境中验证了这种行为,但无论如何都需要Selenium。此外,我们目前还没有使用量角器。我正在寻找Selenium的解决方案。

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

在C#Selenium测试中,我写了:

// 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.

在这个阶段,我几乎没有想法。难道没有办法让Selenium与angularjs玩得很好吗?类似的问题:Selenium click event does not trigger angularjs ng-click没有确定的答案。

2 个答案:

答案 0 :(得分:1)

我建议,使用xpath来定位元素,你应该很好。如果可能的话,请分享xpath。

答案 1 :(得分:0)

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

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