Search code examples
iosswiftxctestxcuitest

In XCUITests, how to wait for existence of several ui elements?


What is the best way to wait for existence of multiple XCUIElements while doing UITests in XCode?


Solution

  • I found this code to be working. We run a loop for a timeout duration, waiting 1 second between the iterations. On every step we check if all the elements exist, return true if they do, continue otherwise.

    func waitForExistenceOfAll(elements: [XCUIElement], for timeout: TimeInterval) -> Bool {
            guard elements.count > 0 else {
                return true
            }
            let startTime = NSDate.timeIntervalSinceReferenceDate
            while (NSDate.timeIntervalSinceReferenceDate - startTime <= timeout) {
                var allExist = true
                for element in elements {
                    if !element.exists {
                        allExist = false
                        break
                    }
                }
                if allExist {
                    return true
                }
                sleep(1)
            }
            return false
    }