What is a good IF statement to use in my Appium code - java

New to the site and still trying to get the hang of asking questions.
UPDATE
Ok so after making some changes to my code I now have this IF statement in my code, but my problem is if the IF statement is true then it proceeds to that certain page but however won't click on the button. Is my code correct or am I missing some parts?
driver.findElement(By.id(redButton)).click();
driver.findElement(By.id(good)).click();
driver.findElement(By.id(locator)).click();
//IF statement with variable named "viewdets"
//If "View Details & Pay" button pops up click
if (!driver.findElements(By.id(viewdets)).isEmpty()) {
driver.findElement(By.id(viewdets)).click();
//App Closes and Doesn't Click Pay Button
driver.findElement(By.id(pay)).click();
driver.findElement(By.id(conpay)).click();
//If not then continue to stall and check in
} else {
Thread.sleep(7000);
driver.findElement(By.id(stall)).click();
driver.findElement(By.id(two)).click();
driver.findElement(By.id(three)).click();
driver.findElement(By.id(next)).click();
wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id(pay)));
driver.findElement(By.id(pay)).click();
driver.findElement(By.id(conpay)).click();
driver.findElement(By.id(receipt)).click();

You can probably assert that the next expected element is present on the screen or not.
Assuming the previous two clicks("View Details & Pay" button) if were successful would lead you to this screen or else not.
org.junit.Assert.assertFalse(driver.findElements(By.id(good)).isEmpty());
validate that there exists an element with id good in the page you have navigated to. And then perform an action over it as:
driver.findElement(By.id(good)).click();

Related

Selenium loop through list and make same actions with every element with java

I`ve seen many info regarding how to implement loops, but I still did not find anything that would solve my problem.
Process of a test:
click on username (which is a link)
uncheck a checkbox for the first groupname
check a checkbox for the next groupname
click saving button (after that you are being automatically redirected to a page with users list and assigned groups)
check that that same name of a group is seen as was assigned
repeat
I have written a test that does all those steps in repeatable step-by-step form, but it would be better to turn it into a loop and that where I encounter a problem. For now my code looks like this:
driver.findElement(By.linkText("testUser")).click();
WebElement parent = driver.findElement(By.xpath("/html/body/app-root/app-admin-edit-user-profile/main/div[2]/div/form/section[2]/div[2]"));
List<WebElement> children = parent.findElements(By.className("custom-checkbox"));
for(int i = 0; i < children.size(); i++) {
children.get(i).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
avp.getSaveBtn().click();
driver.findElement(By.linkText("testUser")).click();
}
And it clicks on the user name, clicks on the first group, clicks on it again and clicks save button, and the stops. So basically it performs one action with one group and stops. Could anyone help with that?

How to verify that html is stable (finished changing) in Selenium WebDriver?

I'm testing online Game here http://slotmachinescript.com/
I want to create a test to verify if credits value is the same after page refresh
public class VerifyGameAfterRefresh extends BaseTest{
#Test(invocationCount = 1)
public void testAfterRefresh(){
GamePage gamePage = new GamePage(driver);
gamePage.isLoaded();
int times = getRandInt(2,5);
//change bet value
gamePage.clickSpinUpButton(times);
//click on spin button
gamePage.clickSpinButton(times);
int creditsValue = gamePage.getCreditsValue();
gamePage.pageRefresh();
int creditsValueAfterRefresh = gamePage.getCreditsValue();
Assert.assertEquals(creditsValue,creditsValueAfterRefresh,"Credit after refresh are not the same");
Assert.assertTrue(gamePage.getBetValue() == 1, "Bet value was not set to default");
}
}
Method to get creditsValue :
public int getCreditsValue(){
//wait.until(ExpectedConditions.
int value = Integer.parseInt(creditsValue.getText());
return value;
}
Everything works perfect until the case when after last click on spin user wins. In this case <span id="credits">value</span> value is changing dynamically, but my method does not wait till the end of the changing and grab the value at the beginning that after leads to test fail.
May I use some functionality of
wait.until(ExpectedConditions.
just to wait for my value to be stable?
Or what would you recommend?
Unfortunately there is no easy way to track whether page was refreshed or not, you could do smthn like ExpectedConditions.refreshed and ExpectedConditions.stalenessOf(WebElement). However the problem is, there is now way for webdriver to find out whether refresh already happened or it's going to happen in the future.
Best way to do it is to wait for smthn that actually changes to change, i.e. you're clicking button and see that state of button changes back and forth. Or maybe some other elements on page change? Also, be aware of the fact if page itself remains the same you may end up having StaleReferenceException in this case it'll be necessary to implement custom ExpectedCondition.
Alternatively you could try to do following things:
Wait for document.ready state
Wait for ajax state by checking jQuery.active state

Selenium Java - Click if element exists, continue with the next command if element not found

i'm trying to create a script to test a web site (js application), code is almost done but i encounter a problem. The script its supposed to edit a question on the website (the question uses a lot of variables from a database) and depending on were the script failed or if anyone else edited the question there is a chance for the script to get a pop-up message(not a separate window or new tab). I want the code to:
Click the element if present or go to the next line of code if the element does not exist.
I tried using but it does not help:
Alert alert = driver.switchTo().alert();
alert.accept();
My code:
driver.findElement(By.xpath("//button[2]")).click();
// Click unselect all
Thread.sleep(1000);
driver.findElement(By.linkText("Romania")).click();
// Select Romania
log.debug("Select Romania");
Thread.sleep(2000);
driver.findElement(By.linkText("Germany")).click();
// Select Germany
log.debug("Select Germany");
Thread.sleep(2000);
driver.findElement(By.xpath("//div[4]/a")).click();
// Click Save Button
log.debug("Click Save");
Thread.sleep(3000);
**driver.findElement(By.xpath("//div[4]/div/div/div/div/div/button")).click();**
// Pop-up message
log.debug("Click Pop-up message");
Thread.sleep(3000);
/////////////// Single Answer
driver.findElement(By.linkText("Change")).click();
// Click Change Template
log.debug("Click Change");
Thread.sleep(2000);
The you can find the line with the issue between **** (pop-up), how can i click if the element exists or move to driver.findElement(By.linkText("Change")).click(); if element not found.
Please let me know if more info is required.
Edit:
To give more details about why the pop-up appears. The script edits a question, the questions have multiple templates and the script is supposed to go through each template after selecting the template the script will associate a variable from the database to the question.
Templates:
Single answer question
Single answer dropdown question
Multiple answer question
Multiple answer dropdown question
Date
The pop-up message appears as a warning (that the variable used will be removed )when the template is changed from multiple answer to single answer/date or the other way around.
In the perfect case if the script finishes successfully (it will end with single answer dropdown - first question is single answer so the pop-up does not appear )and no one edits the question i will not encounter the pop-up but if the script fails due to x reason after changing the template to multiple answer, when i restart the script i will receive that pop-up/warning.
The issue also occurs when changing the language of the question as shown in the code above, i have multiple steps were i encounter this problem.
At the moment in order for the script to run and avoid the problem mentioned above, i need to edit the question myself and select a specific language and template before running the script.
If no matching elements are found, an instance of NoSuchElementException is thrown.
try {
WebElement popUp = driver.findElement(By./**your expression**/);
popUp.click();
} catch(NoSuchElementException | StaleElementReferenceException e) {
log.debug("Impossible to click the pop-up. Reason: " + e.toString());
}
I'd recommend two approaches.
Simply poll the DOM for the pop-up and click the button if exists:
List<WebElement> button = driver.findElements(By.xpath("//div[4]//button"));
if (!button.isEmpty()) {
button.get(0).click();
}
....
driver.findElements() is used to avoid try-catching NoSuchElementException in case using driver.findElement()
You may use explicit wait to wait some time for the button to appear:
try{List<WebElement> button = (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementsLocated(By.xpath("//div[4]//button")));
if (!button.isEmpty()) {
button.get(0).click();
}
}
catch(TimeoutException e)
{
}

Selenium alert only shows in debug mode

I am testing a site page using Webdriver/Java which contains many fields. One of the fields is a dropdown box (or select box) and it contains validation upon losing focus (e.g. tabbing out). So if I select a particular option in the dropdown and tab to the next field, an alert box will pop up saying "You cannot choose that!".
Now I am doing code that checks for the presence of the alert box, and accepts it, however this is only working for me in DEBUG mode. When running the test (i.e. not in debug) I get "Timed out after 10 seconds waiting for alert to be present Build info: version: '2.53.0'".
I understand that this is probably a timing issue since it works in DEBUG mode, but I can't understand why as I'm using ExpectedConditions.alertIsPresent(). The code where this is failing is here:
WebElement currentElement = driver.findElement(By.id("selectbox"));
Select currentSelect = new Select(currentElement);
currentSelect.selectByVisibleText(updatedValue);
currentElement.sendKeys(Keys.TAB);
System.out.println("milestoneA");
if ((exceptionExpected()) {
System.out.println("milestoneB");
wait.until(ExpectedConditions.alertIsPresent());
System.out.println("milestoneC");
checkAlertBox(getExpectedResultFromExcel());
}
In DEBUG mode, the code keeps going fine and all is good. In RUN mode in my logs I get up to milestoneB and then the above mentioned error is thrown.
Further to this, if I add a Thread.sleep(1000) before Tabbing, all works fine.
Any ideas please?
I would try to send the TAB key until the element loses the focus:
WebElement currentElement = driver.findElement(By.id("selectbox"));
currentElement.click();
currentElement.sendKeys("abcd");
// wait for the popup to be visible
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#abc")));
// send the TAB key while the current element has focus
new WebDriverWait(driver, 20).until((WebDriver wd) -> {
currentElement.sendKeys(Keys.TAB);
return !wd.switchTo().activeElement().equals(currentElement);
});

How to find "Cursor" position in webpage with Selenium Webdriver?

I just started learning Selenium Webdriver using java Script, the question what I have asked might me a silly one. But still wanted to know whether it is possible or not.
As per my question, please go through the below example
In any Login page, enter valid "Username" and click on "signin" button, it throws an error message "Please enter password" and the "cursor" will be located in "Password" field
So, we can get the error message via code. Now, how can we locate or identify the "Cursor" position in the webpage via code?
By definition, any widget that has focus also has the cursor. So driver.switchTo().activeElement() will return the currently focused WebElement. It doesn't actually change anything, just returns the active element. You can call
expectedElement.equals(driver.switchTo().activeElement());
to verify that expectedElement has focus.
Hey user3313128 with Selenium Web driver library it is only possible to figure out the current position by knowing the last place you moved it to.
Javascript sadly dose not give you an option to quickly get the X & Y.
An easy work around this is to simple run an simple function in the browser
async function (){
await this.driver.executeScript(function( ) {
let mouse = { x:0, y:0 }
onmousemove = function(e){ mouse.x = e.clientX, mouse.y = e.clientY }
})
}
this function will track your mouses X and Y in the browser the whole time
Then when you need to know mouse's location just call this script
mouse = driver.executeScript( function (){return mouse})
although the smart move is to track all of this within your JS on the server side at each mouse move and click().

Categories

Resources