Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of XCUIElement in XCUIElementQuery?

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?

like image 623
Bartłomiej Semańczyk Avatar asked Aug 23 '15 09:08

Bartłomiej Semańczyk


2 Answers

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.

like image 191
Alex Avatar answered Oct 05 '22 22:10

Alex


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.

like image 24
Sulthan Avatar answered Oct 05 '22 23:10

Sulthan