Verify an element is not existing using webdriver and selenium - javascript

I'm using WebdriverIO and selenium-standalone to write automated tests that will verify that various parts of our user interface are working.
I need to verify that an element is not present on the page. For example, our system allows staff to track various types of resources that we are referring clients to. If a staff member accidentally adds the wrong resource, they can delete it, and I want to verify that the resource was actually deleted and is not present on the page.
WebdriverIO has an .isExisting() property, but no way to check if something is not existing (or not visible/present). I could also use Chai assertions to figure this out, but haven't delved into that world yet.
Here's a snippet of my code:
it('I can delete a resource from a need', function() {
return driver
.moveToObject('span.ccx-tasklist-task') // Hover mouse over resource
.click('div.referral-controls a.btn.dropdown-standalone') // Click Resource drop-down
.click('div.referral-controls.ccx-dropdown-menu-selected li > a') // Delete Resource
.pause(2000);
// Need to Verify that resource was deleted here
Any advice? Let me know if you need more information.

You can waitForExist with the reverse option set to true.
.waitForExist( '[id$=OpenNeedsPanel] div.commodities', 500, true )

I was able to verify that an element didn't exist on the page like this:
.isExisting('[id$=OpenNeedsPanel] div.commodities').should.eventually.equal(false);

you can simply use the below mentioned line of code
int temp=driver.findElements(By.xpath("your x-path expression")).size();
you can even replace your xpath locator with your other locators as well like id,class,link etc.
Now, if the value of temp>0, it means , your element exists

You can refer https://webdriver.io/docs/api/element/waitForExist.html
Wait for an element for the provided amount of milliseconds to be present within the DOM. Returns true if the selector matches at least one element that exists in the DOM, otherwise throws an error. If the reverse flag is true, the command will instead return true if the selector does not match any elements.
resource.waitForExist(1000, true);
where 1000 is the timeout in ms.

Related

Cypress unable to find selector - React/CSS Modules/Cypress

I am writing e-2-e tests for our frontend using Cypress.
When I try to target an element, I am using .button-module_btnLabel__30kQb, but as I understand this makes my test brittle as the classname hash may change.
However, when I try to add a selector, Cypress can't find it. An example below:
import { Button } from '...ui'
<Button.Primary
data-cy="submit"
onClick={startLogin}
>
Log In
</Button.Primary>
cy.get('data-cy="submit"')
.should('be.visible')
.should('contain.text','Log In')
.click()
AssertionError: Timed out retrying after 4000ms: Expected to find element: `[data-cy=submit]`, but never found it.
If you are selecting on an attribute, you need enclosing square brackets.
cy.get('[data-cy="submit"]')
Note React does not pass on all attributes, but data prefix should be ok.

Protractor - Jasmine . Perform some action only when a specific element is present.

I have a window-box with two buttons 'add' and 'close'. I need to test below scenario:
When clicked on 'add' button it throws error and the window remains open. I need to click on 'close' button to proceed.
I used below code:
if(element(by.xpath("xpath_of_error_box")).isEnabled())
{
element(by.xpath("xpath_of_close_button")).click();
}
But it throws below error:
No element found using locator: By(xpath, xpath_of_error_box)
Is there any way to handle this?
According to the error, it seems that your xpath locator didn't match any element. And according to the additional clarification in the question you could try:
element(by.xpath("xpath_of_error_box")).isDisplayed().then(isDisplayed => {
if (isDisplayed) {
// do what you need when it is visible
} else {
// if not then proceed
}
});
As it was pointed out, isEnabled might not be the proper method you should use in this case. If it seems that the element you try to find is always present in the dom, you might better try to check for its visibility using isDisplay instead.
An advice. It's not a good idea to use xpath locators in your tests, because this ties them to the html DOM structire of the web page you are observing. As we know, the UI happens to change often, which would make your tests to brake often as well. Although this is of cource a personal preference, it is such until you end up with tons of brocken tests after a single small change in the html.
If you need to check if an element is present you can use the following code:
if (element(by.xpath("yourXpath")).isPresent())
But your problem is not on your if code, your problem is that the xpath your are searching doesn't exist.
isEnabled() and isPresent() returns promise (not boolean) and have to be resolved.
isEnabled() could be only used for <button>.
You can use XPath all the time, don't listen to anyone.
PS. Of course it would be glad to see your HTML to check the correctness of your XPath.

Functionally test that an Element is visible (no elements covering) with Intern

I am currently using the JavaScript framework Intern to test my site, I am wanting to ensure that specific element's are truly visible. Intern currently has an option "isDisplayed" which half does this. But what I am wanting to also do is check that it would be truly visible to the user and that any other elements on the page do not cover (perhaps by z-index issues) etc.
Does anyone have an suggestions?
Thanks in advance.
Usually, it's better to focus on your unit tests and make sure the styles you expect to be setting are coming back correctly from the utility/helper functions you use to do so. Otherwise, you're going to end up testing things you probably don't mean to, such as functionality of the browser itself to compute the styles. Therefor, it's bad practice in many situations.
However, if you do need this, such as when testing a 3rd party JavaScript library against a customer's site, Intern's Leadfoot provides a .execute() method you'll want to use.
Example:
return this.remote // represents the browser
.get('mysite.com') // navigate to a page
.execute( // send a callback to the browser
function (selector) {
var elem = document.querySelector(selector),
result;
// collect some data for analysis...
result = getComputedStyle(elem).zIndex;
return result;
},
['div'] // arguments to send to the remote callback
)
.then(
function (zIndex) {
// analyze the data and make assertions about it...
assert(zIndex > 999);
}
);
Please note: This is awesome but be careful. Most of your test runs inside of Node.js, but the callback to .execute() does not and so it does not have access to any of your previously defined variables, etc.
As for strategies to determine when an element is truly visible to the user, it's very subjective, but getBoundingClientRect() is going to be your friend for determining when one element is overlapping another. There are good techniques here: Determine visibility / real z-index of html elements

How to identify a hidden file element in selenium webdriver

Team,
I am trying to automate a file upload functionality but webdriver doesn't recognize the file object. Here is the thing:
The file object is in a modalbox (xpath is of the modal box is //*[#id='modalBoxBody']/div[1]). The type and name of the file object are file and url respectively.
When i see the html content, there are two objects with the same attributes. One of them is visible and another is invisible. But the hierarchy they belong to are different. So I am using the hierarchy where the element is visible.
Following is my code. I have tried all possible solutions provided in the stackoverflow (as much as I could search), but nothing worked. Commented out sections mean that they too are tried and failed.
wbdv.findElement(By.xpath("//*[#id='left-container']/div[4]/ul/li/ul/li[2]/a")).click();
wbdv.switchTo().activeElement();
System.out.println(wbdv.findElement(By.xpath("//*[#id='modalBoxBody']/div[1]")).isDisplayed()); **//This returns true**
List<WebElement> we = wbdv.findElement(By.xpath("//*[#id='modalBoxBody']/div[1]")).findElement(By.className("modalBoxBodyContent")).findElements(By.name("url")); **//There is only one element named url in this hierarchy**
System.out.println(we.isEmpty()); //This returns false meaning it got the element named url
//((JavascriptExecutor) wbdv).executeScript("document.getElementsByName('url')[0].style.display='block';"); **//This didn't work**
for(WebElement ele: we){
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) wbdv).executeScript(js, ele);
System.out.println(ele.isDisplayed()); **//This returns FALSE**
System.out.println(ele.isEnabled()); **//This returns TRUE**
System.out.println(ele.isSelected()); **//This returns FALSE**
ele.click(); **//This throws org.openqa.selenium.ElementNotVisibleException exception**
}
Now, if you look at the 3 methods above, it seems that the element is NOT displayed, NOT selected but IS enabled. So when it is not displayed, selenium cannot identify it. The java script to make it visible also came to no rescue.
Could anyone please help me solve this. It ate my entire day today?
In your last example, it looks to me like you have the right idea with using the 'style.visibility' tag. Another thing that I would recommend trying is using "ExpectedConditions.visibilityOfElementLocatedBy" method. Usually I use "presenceOfElementLocatedBy", but if you are talking about the css visibility property, I think using "visibilityOfElementLocatedBy" is the way to go. I think what might be happening for you is that you need the wait condition on the element object you are trying to get a hold of and the "ExpectedCondtions" method should give you what you need. I see that you have tried a few things but you haven't listed using a Wait condition. No guarantees, but you should try it:
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath(".//whatever")))

How to use condition in a TestGen4Web script for a child popup window?

I have TestGen4Web script for automating testing on a web-based user interface that has a popup window (hey i didn't write that ui..). In order to write a complete test script that branches the flow based on the some presence of some content in the popup window, I need to write a simple if condition that does something like if document.getElementById("xyz").value - that will run on the popup window and not the parent window.
Any ideas on how to accomplish this? currently, the condition fails because it runs on the parent window.
Also, how to extract some text from the dom and spit it out to a file at the end of the test?
Talked with the author of TestGen4Web. He concluded this was a bug and will be fixed in the next release. Here is the email with the temporary workaround fix:
I have a fix for your problem - which I will add in the next release.
Until then, you can use this patch.
Under your profile's
extensions/{3c20433a-61bc-42fe-831d-415860e17283}/chrome/recorder/cont
ent/
directory,
find recorder.js under the extension installation directory.
in recorder.js, find the method named
Recorder.prototype.fixAction = function(action) {
just before the return method, add the following 2 lines.
newAction.winref = this.fixDatasetsAndVariables(newAction.winref);
newAction.pagerefreshed =
this.fixDatasetsAndVariables(newAction.pagerefreshed);
restart firefox, and run your test.
Hope that solves your problem. Let me know if there are more issues
with the fix.
outside your loop initalize a loop count variable initialize it to
"1" ('count', in the attached example) 2. replace all "tg4wnamed1" with
"tg4wnamed${count}"
outside your loop initalize a loop count variable initialize it to
"1" ('count', in the attached example) 2. replace all "tg4wnamed1" with
"tg4wnamed${count}"

Categories