How to check an element's existence after a loading animation in a UI Test? Swift

Viewed 213

The problem is simple: How to check an element's existence after a loading animation in a UI Test? BUT without using static timeouts.

For example: If animation lasts 3 seconds ui test waits for 3 seconds, if animation lasts 10 seconds ui test waits for 10 seconds or is there another way around it?

I'm trying to wait as long as my api call lasts simply

1 Answers

You can tackle this in one of two two ways: 1) Wait for your element to exist or 2) Wait for the animation to disappear.

In order to wait for your element to exist, you'd use Apple's waitForExistence function with a long timeout on your target element. This returns a boolean so you can simply assert directly on it.

XCTAssertTrue(myElement.waitForExistence(timeout: 15.0)) // wait for 15 seconds maximum

In order to wait for your animation to disappear, you'd identify it, and extend XCUIElement with the following function, which I use extensively and therefore bundle into my XCToolbox Cocoapod. You'd then be able to check the exists property on your target element.

public func waitForDisappearance(timeout: TimeInterval = Waits.short.rawValue) -> Bool {
    let expectation = XCTNSPredicateExpectation(predicate: NSPredicate(format: UIStatus.notExist.rawValue), object: self)
    let result = XCTWaiter.wait(for: [expectation], timeout: timeout)
    switch result {
    case .completed:
        return true
    default:
        return false
    }
}

This code would look like the following:

_ = animationElement.waitForDisappearance(timeout: 15.0)
XCTAssertTrue(myElement.exists)

Neither solution is wrong. The first is less code and arguably cleaner, the second is more explicit and possibly more readable.

Related