I am trying to create a method the returns False when a specific label is not found. However, the method continues to return True and my test is failing.
public bool DeliveredDisplayed()
{
Boolean labelDisplayed = session.FindElementByName("Delivered").Displayed;
return labelDisplayed;
}
Assert.IsFalse(OrderHistory.DeliveredDisplayed(), "The order is still delivered");
Are You sure, this particular "FindElementByName" method did not have possibility to find another element with such a Name? We are using "Displayed" property and it is working fine.
Maybe better is to use "AutomationId" or in case where You need to check for one particular item where on page there are bunch of others with name "Displayed", XPaths?
Related
I am working with taiko and gauge right now and have several asserts as e.g.
assert.ok(text("example").exists())
But now I delete some text parts and want to check that the text really is deleted.
I tried
assert.equal(text("example").exists(), false)
but that fails.
I suppose that exists() doesn't return booleans since assert.equal(text("example").exists(), true)also fails, while the above .ok is correct.
Is there any function like assert.notOk(text("example").exists())?
Thanks for your help in advance!
text("example").exists() waits for the text and fails if the text is not available on the page after specific interval of time.
Try using exists function as follows
text("example").exists(0,0) // i.e. (retryInterval, retryTimeout)
This will check the page immediately and return a boolean.
You can add the expected result (true or false) to your assert:
assert.ok(text("example").exists(), false)
This will result in a true if the search pattern does not exists.
This line of code:
$this->fillField('xpath','//fieldset[#id="address-container"]/input[#name="address_add[0][city]"]', "Toronto");
Is giving me this error
Form field with id|name|label|value|placeholder "xpath" not found. (Behat\Mink\Exception\ElementNotFoundException)
The reason I want to use xpath in my fillField is because there are actually multiple input[#name="address_add[0][city]"] in my html document. I figure an xpath will let me target specifically the field I want to populate.
What's the best way to fill out just the input[#name="address_add[0][city]"] that is a descendant of fieldset[#id="address-container"] ?
You are not using the method in the wright way.
As i see here xpath is taken as selector.
The method expects 2 parameters:
identifier - value of one of attributes 'id|name|label|value'
value - the string you need to set as value
If you want to use css|xpath then you need to use find method first.
For example:
$this->find('xpath', 'your_selector')->setValue('your_string');
Please note that find might return null and using setValue will result in a fatal exception.
You should have something like this:
$field = find('xpath', 'your_selector');
if ($field === null) {
// throw exception
}
$field->setValue('your_string');
Also your selector could be written as:
#address-container input[name*=city] - this with css
or
//fieldset[#id="address-container"]//input[contains(#name, 'city')] - this with xpath
Make sure you take advantage of your IDE editor when you have any doubts using a method and you should find a php doc with what parameters are expected and what the method will return.
If you are using css/xpath a lot you could override find method to detect automatically the type of selector and to use it like $this->find($selector);
Also you could define another method to wait for the element and to handle the exception in one place, for example waitForElement($selector) that could contain a conditional wait up to 10 seconds and that throws exception if not found.
I am creating a script that involved searching for a record and then updating the record. On the search screen, the user has the option of viewing advanced search options. To toggle showing or hiding advanced search is controlled by one button.
<a title="Searches" href="javascript:expandFilters()"><img border="0" align="absmiddle" alt="Advanced" src="****MASKED URL****"></a>
The only difference between the properties of the search button when it is showing or hiding the advanced search is the img src:
When advanced search is hidden the IMG src ends with "/Styles/_Images/advanced_button.jpg", when advanced search is visible, the IMG src ends with "/Styles/_Images/basic_button.png"
When I open the page, sometimes the Advanced search options are showing, sometimes they aren't. The value that I want to search on appears in the Advanced section, so for my script to work I have added an IF statement.
<input type="text" value="" maxlength="30" size="30" name="guiSystemID">
The IF statement looks for the fields that I need to enter data into, and if the field does not exist then that would indicate that the Advanced options are not visible I need to click on the button to expand the search option.
I created the following IF statement.
if (!driver.findElement(By.name("guiSystemID")).isDisplayed()) {
driver.findElement(By.cssSelector("img[alt='Advanced']")).click();
}
When I run the script and the Advanced search is expanded then the script runs successfully. However, when I run the script and the Advanced search is not expanded, the script fails, advising me that it could not find the object "guiSystemID". This is frustrating because if it can't find it then I want the script to continue, entering into the True path of the IF statement.
Has anyone got any suggestions about how else I could assess if the field is appearing without having the script fail because it can't find the field.
Thanks in advance
Simon
I might be late in answering this, but it might help someone else looking for the same.
I recently faced a similar problem while working with isDisplayed(). My code was something like this
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**Do this*/
}
else
{
/**Do this*/
}
This code works pretty well when the element that isDisplayed is trying to find is present. But when the element is absent, it continues looking for that and hence throws an exception "NosuchElementFound". So there was no way that I could test the else part.
I figured out a way to work with this(Surround the {if, else} with try and catch block, say something like this.
public void deleteSubVar() throws Exception
{
try
{
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**when the element is found do this*/
}
}
catch(Exception e)
{
/**include the else part here*/
}
}
Hope this helps :)
I've had mixed results with .isDisplayed() in the past. Since there are various methods to hide an element on the DOM, I think it boils down to a flexibility issue with isDisplayed(). I tend to come up with my own solutions to this. I'll share a couple things I do, then make a recommendation for your scenario.
Unless I have something very specific, I tend to use a wrapper method that performs a number of checks for visibility. Here's the concept, I'll leave the actual implementation approach to you. For general examples here, just assume "locator" is your chosen method of location (CSS, XPath, Name, ID, etc).
The first, and easiest check to make is to see if the element is even present on the DOM. If it's not present, it certainly isn't visible.
boolean isPresent = driver.findElements(locator).size() > 0;
Then, if that returns true, I'll check the dimensions of the element:
Dimension d = driver.findElement(locator).getSize();
boolean isVisible = (d.getHeight() > 0 && d.getWidth() > 0);
Now, dimensions, at times, can return a false positive if the element does in fact have height and width greater than zero, but, for example, another element covers the target element, making it appear hidden on the page (at least, I've encountered this a few times in the past). So, as a final check (if the dimension check returns true), I look at the style attribute of the element (if one has been defined) and set the value of a boolean accordingly:
String elementStyle = driver.findElement(locator).getAttribute("style");
boolean isVisible = !(elementStyle.equals("display: none;") || elementStyle.equals("visibility: hidden;"));
These work for a majority of element visibility scenarios I encounter, but there are times where your front end dev does something different that needs to be handled on it's own.
An easy scenario is when there's a CSS class that defines element visibility. It could be named anything, so let's assume "hidden" to be what we need to look for. In this case, a simple check of the 'class' attribute should yield suitable results (if any of the above approaches fail to do so):
boolean isHidden = driver.findElement(locator).getAttribute("class").contains("hidden");
Now, for your particular situation, based on the information you've given above, I'd recommend setting a boolean value based on evaluation of the "src" attribute. This would be a similar approach to the CSS class check just above, but used in a slightly different context, since we know exactly what attribute changes between the two states. Note that this would only work in this fashion if there are two states of the element (Advanced and Basic, as you've noted). If there are more states, I'd look into setting an enum value or something of the like. So, assuming the element represents either Advanced or Basic:
boolean isAdvanced = driver.findElement(locator).getAttribute("src").contains("advanced_button.jpg");
From any of these approaches, once you have your boolean value, you can begin your if/then logic accordingly.
My apologies for being long winded with this, but hopefully it helps get you on the right path.
Use of Try Catch defies the very purpose of isdisplayed() used as If condition, one can write below code without using "if"
try{
driver.findElement(By.xpath(noRecordId)).isDisplayed();
//Put then statements here
}
Catch(Exception e)
{//put else statement here.}
Scenario: I have a scenario like after login to some page, a profile update button intermittently appears which i need to click on. Thing is like if that button will appear i have to click otherwise i have to leave that part and go ahead. I have written a logic to handle that scenario like below.
public boolean isElementPresent(By locatorKey) {
try {
getDriver().findElement(locatorKey);
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
If that element will appear it will return true otherwise it will return false.. The above code is working fine...but the problem is it is taking around one min to return either true or false..suppose i have used five places in my script so unnecessarily i the script is waiting for 5 mins...I have also tried the below code
getDriver().findElement(locator).isDisplayed();
But the same issue i am facing ...the code is working fine but it is also taking around 1 min to return the command...
Is there any efficient way to handle this kind of scenario without waiting one min to get the status?
Use method findElements instead, and check if the returned list is not empty:
return !getDriver().findElements(locatorKey).isEmpty();
Please note that a try/catch clause is not required here.
barak manos has a perfectly viable answer to your question, but if you'd like to avoid the boolean inversion, here is an alternative:
public boolean isElementPresent(By locatorKey){
return (getDriver().findElements(locatorKey).size() > 0);
}
As with his solution, no try/catch is required for this as findElements() will simply return an empty list if the locator is not found or has gone stale.
Again, not to detract from barak manos here. This is just another solution.
I am trying to test a webpage using Selenium and NUnit. One of my test cases entails the validation of text boxes. Using Selenium and C#, I am able to retrieve the value entered in the text box. But when the validation of the text box fails, an error message is displayed next to the text box.
So, here are my questions:
1. How can I test if an error was raised due to validation failure.
2. Can I get the text of that error.
3. Or, am I way off the mark and what I am trying to do is not at all possible.
I have tried reading the value of the element, but it always seems to be an empty string.
Say, for example, I am trying to test the webpage https://edit.yahoo.com/registration . When I enter "**myname&&" in the First Name field, an error appears stating "Only letters, spaces, hyphens, and apostrophes are allowed". I want to be able to test that this error was raised.
Also, I noticed that when Selenium opens the webpage and enters an incorrect value in the text box, the error message does not get displayed next to this text box. Whereas, when I open the webpage myself and enter an incorrect text, the error message is displayed
Thanks!!
You will have to use thread.sleep, but in a better way. It's better to write a function like this (I am writing this in JAVA, you should be able to write it for C#). This method will wait for the specified number of seconds for the element to be visible. If the element is not visible even after the specified number of seconds, then the method will return false. If it becomes visible then the method will return true.
Alternatively, you can use an assertion instead of returning a false condition so that your test fails.
public boolean waitForErrorMessage(String elementToWaitFor, int waitTimeInSeconds)
{
int timeOut=0;
while(!selenium.isVisible(elementToWaitFor))
{
if(timeOut<waitTimeInSeconds){
#sleep for one second
Thread.Sleep(1000);
}
else {
return false;
}
timeOut=timeOut+1;
}
return true;
}