简体   繁体   中英

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

在 XCode 中执行 UITests 时等待多个XCUIElement存在的最佳方法是什么?

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
}

A slightly more concise version:

func waitForExistenceOfAll(elements: [XCUIElement], for timeout: TimeInterval) -> Bool {
    for _ in 0 ... Int(timeout) {
        if elements.filter({ $0.exists == false }).isEmpty {
            return true
        }

        Thread.sleep(forTimeInterval: 1)
    }

    return false
}

Also check this: https://pspdfkit.com/blog/2016/running-ui-tests-with-ludicrous-speed/

You can use it as basically wait for anything, that will give you Bool as return (multiple conditions etc.)

using variadic functions:

public func exists(_ elements: XCUIElement..., timeout: TimeInterval = 5.0) -> Bool {
    for element in elements {
        if !element.waitForExistence(timeout: timeout) {
            return false
        }
    }
    return true
}

usage:

exists(el1, el2, el3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM