Unable to pick image from gallery XCUITest

401 views Asked by At

I use XCUITest for testing an app that allows the user to select an avatar by picking a photo from the gallery. When I tap on the button that opens the gallery window, I can see the elements in debugDescription. There is a table that contains the folders with photos. The problem is when I tap for the first time on any cell the test fails with error:

Assertion Failure: UserProfileAndSettingsTests.swift:434: Failed to get matching snapshot: No matches found for Element at index 2 from input {(
    Table
)}".  

If I put a breakpoint there, the second time I tap on any cell, it works.

The command is the following:

XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1).tap()

If before the command I put the line: XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1), it doesn't fail. It fails when trying to tap().

1

There are 1 answers

0
lawicko On

Looks like a timing issue. Familiarize yourself with the XCUIElement class, specifically with this:

/** Waits the specified amount of time for the element's exist property to be true and returns false if the timeout expires without the element coming into existence. */
    open func waitForExistence(timeout: TimeInterval) -> Bool

You should be able to do something like this:

let element = XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1)
if element.waitForExistence(timeout: 2) {
   element.tap()
}

I recommend making friends with this method, and also other similar methods and expectations, to be able to do convenient stuff like this (self in this context is a XCTestCase):

func waitUntilTappable(_ element:XCUIElement, timeout: TimeInterval = 2) {
   let tappableExpectation = self.expectation(for: NSPredicate(format: "isHittable == true"),
                                                        evaluatedWith: element)
   self.wait(for: [tappableExpectation], timeout: timeout.rawValue)
}