XCTest - How can I wait for an element from a given array of elements to become visible?

91 views Asked by At

This is the flow I'm trying to cover - after I complete a certain action, some intermediary screens (let's say alerts) may or may not appear. If any of those intermediary alerts are shown, I need to to dismiss them. For this to be completed, I need to wait for at least one element from a given array elements to become visible; the function should return the visible element (out of the array), or time out if none of the elements became visible in the provided time frame.

The function I'm trying to use looks something like:

static func waitForAnyElement(_ elements: [XCUIElement], timeout: TimeInterval) -> XCUIElement? {        
        let app = XCUIApplication()
        let existsPredicate = NSPredicate(format: "exists == true")

        var allExpectentions = [XCTNSPredicateExpectation]()
        
        for el in elements {
            let expectation = XCTNSPredicateExpectation(predicate: existsPredicate, object: el)
            allExpectentions.append(expectation)
        }
        
        let result = XCTWaiter.wait(for: allExpectentions, timeout: timeout) // wait and store the result
        switch result {
        case .completed:
            for el in elements {
                if el.exists {
                    return el
                }
            }
        case .timedOut:
            // One of the elements did not appear within the timeout, the test fails
            XCTFail("Elements did not appear within the timeout")
        default:
            XCTFail("Something went wrong with the wait for multiple elements function.")
        }
        // ===
        return nil

What I'm trying to do is for each element provided to the function, generate a XCTNSPredicateExpectation and store it into an array, so that I can pass that array to the XCTWaiter.wait function. The second thing I'm trying to achieve (and the most important) is to make sure that XCTWaiter.wait function checks the expectations with the OR condition instead of the AND condition.

0

There are 0 answers