How to use “if” operator for Appium tests

2019-07-17 04:59发布

I need to check if button with title "title_I_need" exist. And if exist to press it if not press another one. All this stuff in javaScript.

What I did I recorded in Appium.App test and added verification if button exist. As I'm not familiar with JavaScript to much I started with Objective-C. But as a result it always clicks title_I_need button but my expectation is else branch with other_title button.

Can I do such check with Appium? If yes, How can I do this with JavaScript (node.js)?

#import <Selenium/SERemoteWebDriver.h>

@implementation SeleniumTest

-(void) run
{
    SECapabilities *caps = [SECapabilities new];
    [caps addCapabilityForKey:@"appium-version" andValue:@"1.0"];
    [caps setPlatformName:@"iOS"];
    [caps setPlatformVersion:@"8.4"];
    [caps setDeviceName:@"device_name"];
    [caps setApp:@"/path/AppName.app"];
    NSError *error;
    SERemoteWebDriver *wd = [[SERemoteWebDriver alloc] initWithServerAddress:@"0.0.0.0" port:4723 desiredCapabilities:caps requiredCapabilities:nil error:&error];
    //check for element with wrong not existed title to go to else branch
    if ([wd findElementBy:[SEBy name:@"wrong_title"]]){
    [[wd findElementBy:[SEBy name:@"title_I_need"]] click];
  } else {
    [[wd findElementBy:[SEBy name:@"other_title"]] click];
  }
}

@end

1条回答
一夜七次
2楼-- · 2019-07-17 05:25

The easiest way to do this is to use findElementsBy (notice the s) which will return an array. Then simply check if the array is empty. Put this in a function and call it something like doesElementExists. A corresponding java method to this would be :

public boolean doesElementExists(By by) {
    try {
        List allElements = driver.findElements(by);
        if ((allElements == null) || (allElements.size() == 0))
            return false;
        else
            return true;
    } catch (java.util.NoSuchElementException e) {
        return false;
    }
}
查看更多
登录 后发表回答