sferret sferret - 2 years ago 135
Javascript Question

Selenium.webdriver trying to find a tab text vaue

Hi I am using mocha and node js, and am trying to get selenium webdriver working. The app is a SPA.
All I want to do is get a particular tab, and then click on it.
I have loaded the html into the test OK.
here is a snippet

<div id="Tabs">
<li> <span> one </span></li>
<li> <span> two </span></li>
<li> <span> six </span></li>

In my test.js I have this...

var driver;
var tabs;
driver = new webdriver.Builder()
test.after(function() {

console.log("before got tabs length " + b.length);
test.it("we have some tabs",function(done){
console.log("we have tabs " + tabs.length);
test.it("can find a tab name",function(done){
var span;
for(var i=0;i<tabs.length;i++){
console.log("Field??" + span.getText());
//return span;
}); )};

It passes the "we have some tabs"
but fails "can find a tab name"
with this error

1 failing

1) MYHtml can find tab name:
TypeError: span.getText is not a function

I am trying to find the li - e.g with the span text = 2
so I can click on it.

Answer Source

You have resolved the promise with then and so that returns an array of span items. You should use getText() once the array is returned:

                console.log('Found spans length:'+ spanArray.length);
                spanArray.forEach(function(nextElement) {
                   nextElement.getText().then(function(text) {
                      console.log('Text Found' + text);
                      // An if then check is required here so only
                      // one done is called.
                      if (/*---your condition here ---*/) {

EDIT Code snippet revised above to cope with array and then process each element.

Further Comment Adding @sferret comment regarding the XPATH approach.

Alternatively use XPATH, which can minimise the amount of code and processing needed:

var tab=driver.findElement(By.xpath(".//div[@id='Tabs']/ul/li/span[contains(.,'two')‌​]"));

However care should be taken as xpaths can quickly become a maintenance issue due to the span or div shifting in the example. You have to consider what may change in the page and act accordingly. Is a small amount of more JS code that will not change over time be more of burden than xPaths that in theory could change each week due to where the tab is placed within in the page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download