问题
I have a list of users, presented by table, and I need to search for td element with appropriate value - and if element not exist on current page - click on link to go on another page. I have no ideas how to do this but I used xpath selector to find element with some value.
Each user presented by "tr" element and contains "td" elements inside:
<tr>
<td class="break-all">acceptance</td>
<td>client</td>
<td class="break-all"></td>
</tr>
So, I need to find td element with value = "acceptance", if it's not exist on current page - click on link to go on another page and continue the search.
I found solution, and it works for me!
function isActive(client) {
client.getAttribute("div.right", "class", function (result) {
if (result.value == "right active") {
client
.click("div.icon-caret-right")
.perform(function () {
findByText(client)
})
} else {
//Throw error in this case!!!
}
})
}
function findByText(username, client) {
client.elements("xpath", "//td[text()='" + username + "']", function (result) {
if (!result.value.length) {
isActive(client)
}
})
}
module.exports = findByText;
And I just call findByText(username, client)
.
But now I have another question - how to throw error from else
statement???
回答1:
Maybe something like this, there might be an easier solution though:
function findStringInElementsData(elements, stringToFind, callback)
{
var counter = 0,
numberOfElements = elements.value.length;
elements.value.forEach(function(element){
browser.elementIdText(element.ELEMENT, function(result){
// The string was found, return true
if(result.value === stringToFind) {
return callback(true);
}
// The string was not found return false
if(numberOfElements-1 === counter) {
return callback(false);
}
counter++;
})
})
}
browser
.waitForElementVisible('td', 2000)
.elements('css selector', 'td', function(elements){
findStringInElementsData(elements, "acceptance", function(foundString) {
if(foundString) {
// The string was found
} else {
// The string was not found, click on link to go on another page
}
})
})
The code above will get all td
elements and then call the findStringInElementsData
function which will loop through them to see it their text value is equal to a supplied string ("acceptance" in your case). If the string is found the function will return true, else it will return false.
来源:https://stackoverflow.com/questions/35221127/how-to-create-condition-if-element-not-exist-do-smth-by-using-nightwatch