bbaia / protractor-net

The .NET port of Protractor, an E2E test framework for Angular apps
MIT License
115 stars 72 forks source link

NgBy locators don't throw on non-existing elements #55

Closed otto-gebb closed 7 years ago

otto-gebb commented 7 years ago

Consider the following console application. The comments explain the observed and the expected behavior.

using (var ngDriver = new NgWebDriver(new ChromeDriver()))
{
    ngDriver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5));
    ngDriver.Url = "http://www.angularjs.org";
    ngDriver.FindElement(NgBy.Model("yourName")).SendKeys("Julie");
    // Looking up a non-existing element via NgBy.
    // This should throw as other locators do, but doesn't.
    var element = ngDriver.FindElement(NgBy.Binding("yourName_notfound"));
    // The following line crashes with a NullReferenceException
    // at Protractor.NgWebElement.get_Text()
    // in c: \Users\Bruno\Projets\GitHub\bbaia\protractor-net\src\Protractor\NgWebElement.cs:line 125
    Console.WriteLine(element.Text);
}

Diagnosing NullReferenceExceptions is not very convenient. Compare it to the exception thrown when searching by an unknown id:

An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll

Additional information: no such element: Unable to locate element: {"method":"id","selector":"yourName_notfound"}
otto-gebb commented 7 years ago

A change like this in JavaScriptBy.cs could fix the problem.

@@ -48,7 +48,11 @@ public JavaScriptBy(string script, params object[] args)
         public override IWebElement FindElement(ISearchContext context)
         {
             ReadOnlyCollection<IWebElement> elements = this.FindElements(context);
-            return elements.Count > 0 ? elements[0] : null;
+            if (elements.Count == 0)
+            {
+                throw new NoSuchElementException($"Unable to locate element: {{ {Description} }}.");
+            }
+            return elements[0];
         }

         /// <summary>
bbaia commented 7 years ago

Thanks for the contribution ! Now we have the same behavior than Selenium WebDriver.

As this introduced a breaking change, it will be available in the next major release.

bbaia commented 7 years ago

Available with v0.10