Testing with taiko: assert false - testing

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.

Related

How to assert that a label is not displayed using WinAppDriver

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?

Ignore case Xpath #Name attribute c# Selenium/Appium

I have a C# selenium/Appium project where I need to find a desktop Application window By.Xpath("").
This works:
By.XPath("//*[#Name='ASDASD']");
However, some builds of the app have the window name be "ASDasd", which causes the Xpath above to not find the window element and the test fails.
Is it possible to Ignore the case of the #Name attribute whether it be "ASDASD", "ASDasd" or something else?
I did try using the XPath translate function, but I am not able to find the element, I assume I am doing it wrong.
What I tried:
By.XPath("//*[translate(name(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'asdasd']")
or
By.XPath("//*[translate(name(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'asdasd']")
or
By.XPath("//*[#Name='translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'asdasd'']")
or
By.XPath("//*[#Name='translate(asdasd,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')']")
Maybe some other variations too, but I could not get it to work.
Some of the examples may have invalid formatting.
While other seems to be valid but could not find the element and it would timeout.
UPDATE:
Thank you for the assistance, this worked:
By.XPath("//*[translate(#Name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='asdasd']");
However, it added 60 seconds to the test somehow, it seems to stall for 60 seconds on one of the places where it looks for the main window.
Thanks for the help!
Regards
name() gives you the name of context node. In this case (//*), the name of whatever element you are currently looking at. You meant to write #Name, i.e. the attribute that happens to be called Name.
By.XPath("//*[translate(#Name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'asdasd']")
Using translate() is clunky and fails when the search string contains unanticipated characters.
Unfortunately, there is no lower-case() function in XPath 1.0. But you can work around this limitation with the help of the host language (such as C#).
The following will dynamically create an XPath expression which finds arbitrary values case-insensitively:
var searchValue = "asdasd";
var uc = searchValue.ToUpperInvariant();
var lc = searchValue.ToLowerInvariant();
var xpath = $"//*[translate(#Name, '{uc}', '{lc}') = '{lc}']";
// -> "//*[translate(#Name, 'ASDASD', 'asdasd') = 'asdasd']"

I want to read and display the error message from my application

I intentionally produce the error message below ans I want to validate that error message appears.
The error message :-
Here is my code:
addNewVen.clickOnCreateButton();
WebElement name = driver.findElement(By.xpath("html/body/section/div/div/div/div/p[3]/span"));
String textagain = name.getAttribute("value");
Any suggestions appreciated.
Try isDisplayed method that returns True if element is currently displayed on page and False otherwise:
driver.findElement(By.xpath("html/body/section/div/div/div/div/p[3]/span[text()='Please enter Valid Company Name(Min 3 Chars)']")).isDisplayed();
or shorter option:
driver.findElement(By.xpath("//span[text()='Please enter Valid Company Name(Min 3 Chars)']")).isDisplayed();
I suggest you not to use absolute XPathes, but relative instead
Let me know if this code not works
There are multiple ways by which you can validate this error, I am giving an example for one of them.
Example:
If the error message is fixed you can first of all try to identify this element with the desired text.
WebElement errorMsg = driver.findElement(By.xpath(//span[text()='Please enter Valid Company Name(Min 3 Chars)']));
Once you have the element identified, you can verify it with your Assert statement like:-
errorMsg.isDisplayed();
and return true or false based upon the results and do your validation.

Selenium Webdriver - using isDisplayed() in If statement is not working

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.}

Selenium: How to verify whether an Element is Present

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.