Swift2 UI Test - Wait for Element to Appear

Alex picture Alex · Dec 2, 2015 · Viewed 9.4k times · Source

I want to have a test pause and wait for an element to appear on screen before proceeding.

I don't see a good way to create an expectation for this and wait using

public func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?)

The method to create an expectation I have been using has been

public func expectationForPredicate(predicate: NSPredicate, evaluatedWithObject object: AnyObject, handler: XCPredicateExpectationHandler?) -> XCTestExpectation

But this takes an already existing element, whereas I would like to have the test wait for an element that does not yet exist.

Does anyone know the best way to do this?

Answer

Tomasz Bąk picture Tomasz Bąk · Dec 2, 2015

In expectationForPredicate(predicate: evaluatedWithObject: handler:) you don't give an actual object, but a query to find it in the view hierarchy. So, for example, this is a valid test:

let predicate = NSPredicate(format: "exists == 1")
let query = XCUIApplication().buttons["Button"]
expectationForPredicate(predicate, evaluatedWithObject: query, handler: nil)

waitForExpectationsWithTimeout(3, handler: nil)

Check out UI Testing Cheat Sheet and documentation generated from the headers (there is no official documentation at the moment), all by Joe Masilotti.