How to get index of XCUIElement in XCUIElementQuery?
Asked Answered
B

3

8

This is my simple UITest (customizing order of tabs in tabbarcontroller):

func testIsOrderOfTabsSaved() {

    let app = XCUIApplication()
    let tabBarsQuery = app.tabBars
    tabBarsQuery.buttons["More"].tap()
    app.navigationBars["More"].buttons["Edit"].tap()
    tabBarsQuery.buttons["Takeaway"].swipeLeft()
    tabBarsQuery.buttons["In Restaurant"].swipeLeft()

    //here, how to get position of moved button with text "In Restaurant"?

NOTE:

It is possible to get XCUIElement from XCUIElementQuery by index. Can I do this fro the other way?

Baeza answered 23/8, 2015 at 9:8 Comment(0)
V
9

It seems that the queries automatically return in order based on position on screen.

for i in 0...tabsQuery.buttons.count {
    let ele = tabsQuery.buttons.elementBoundByIndex(i)
}

Where the index i represents the position of the button in the tab bar, 0 being the leftmost tab, i == tabsQuery.buttons.count being the rightmost.

Voltage answered 27/8, 2015 at 14:27 Comment(1)
Note these days it's .element(boundBy: i)Freak
A
5

You have various ways to create a position test. The simplest way is to get buttons at indices 0 and 1, then get two buttons by name and compare the arrays are equal: (written without testing)

 let buttonOrder = [tabBarsQuery.buttons.elementAtIndex(0), tabBarsQuery.buttons.elementAtIndex(1)]

 let takeawayButton = buttons["Takeaway"];
 let restaurantButton = buttons["In Restaurant"];

 XCTAssert(buttonOrder == [takeawayButton, restaurantButton])

Another option is to directly get the frame of each button and assert that one X coordinate is lower than the other.

To answer your specific question about getting the index of an XCUIElement in a XCUIElementQuery, that's absolutely possible. Just go through all the elements in the query and return the index of the first one equal to the element.

Araarab answered 27/8, 2015 at 14:42 Comment(1)
@netshark1000 Thanks, updated to use elementAtIndex.Araarab
C
0

An XCUIElement alone isn't able to tell you its position in within the XCUIElementQuery. You can search the XCUIElementQuery to discover its offset if you know something about the XCUIElement. In the below let's imagine that "More" is the identifier (change 'identifier' to 'label' if that is what you're working with).

If you want to find the offset of the "More" button (as posted in the original question) then:

var offsetWithinQuery : Int? = nil  // optional since it's possible the button isn't found.  
for i in 0...tapBarsQuery.buttons.count{
    if tapBarsQuery.elementAtIndex(i).indentifier == "More" {
       offSetWithinQuery = i
}

After the above loop exits, you'll either have the offset or it'll be nil if "More" isn't found.

Cody answered 27/9, 2018 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.