1

We use selenium in Java to automate our tests in our projects. Some UI pages are are developed with Angular; there selection of elements often fails and the only way to proceed with our testing is to resort to running some JavaScript (via the JS executor).

Is this approach valid or is it considered a bad practice?

  • 1
    I belive you're using the wrong strategy to select your elements. There might be a lot of dynamically generated things which you problable do not take into account. thant's why your selection fails. – Alexey R. Sep 6 '17 at 12:04
1

If using javascript via JS executor is the only way you can access the item, then it can't be a bad practice.

Some alternatives you might like to consider, because this approach can be complex and fragile:

  • If you can convince the developers to ensure that each element on a page has a unique, unchanging identifier you can use that. Even if you have to get it via a custom attribute.
  • If you aren't able to have the developers give you something accessible, the next step is to look for the closest element in the DOM that you can access via Selenium, then go through that element's children/siblings to locate the element you need.
  • Don't be afraid of using a search for elements that contain a specific string. You can do something like findElements(By.TagName, "div") then within the element collection filter out the ones that contain the text you're looking for. (In C# I would use Linq: findElements(By.TagName, "div").Where(el -> el.InnerHtml.Contains("my search string")). A java expert would need to tell you how to get the same result using java).
  • You should be able to use multiple findElements() statements to narrow down your results.
  • If nothing else works, you can then use the JS Executor for your final search or to manipulate an element that is otherwise not able to be modified (such as some date selectors that do not permit text entry: I've used selenium find methods to locate the date selector, then JS Executor to enable it in order to enter a date).
  • Hi Kate. Thanks a lot. Actually I did the first three steps with no luck and then I had to use javascript. I am almost in the same situation, I need to open a small menu which consist of links and then click on them. I will give a try to findElements as well. Thank you. – user1343454 Sep 7 '17 at 7:54
  • @user1343454 - I've run into the same issue in places. Dynamically loading javascript can be a pain to deal with, and the JS Executor can be the only way to handle it at times. – Kate Paulk Sep 7 '17 at 11:42
  • +1 i gave a try to protractor and didn t have all these issues – user1343454 Sep 8 '17 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.