Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save quangDecember/37e2902e4d74855349921eefc96f13ab to your computer and use it in GitHub Desktop.

Select an option

Save quangDecember/37e2902e4d74855349921eefc96f13ab to your computer and use it in GitHub Desktop.
wait for existence in UI testing
import XCTest
class BaseTestCase: XCTestCase {
let app = XCUIApplication()
// ...
func waitforExistence(element: XCUIElement, file: String = #file, line: UInt = #line) {
let exists = NSPredicate(format: "exists == true")
expectation(for: exists, evaluatedWith: element, handler: nil)
waitForExpectations(timeout: 30) {(error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after 30 seconds."
self.recordFailure(withDescription: message,
inFile: file, atLine: Int(line), expected: true)
}
}
}
}
@mauriciochirino

Copy link
Copy Markdown

Nice helper function. I turn it into a protocol to make it reusable for what it's worth:

import XCTest

protocol ExpectationHelpable { }

extension ExpectationHelpable where Self: XCTestCase {
    func waitForExistence(of element: XCUIElement, file: String = #file, line: UInt = #line) {
        let idleTime: TimeInterval = 1
        let exists = NSPredicate(format: "exists == true")

        expectation(for: exists, evaluatedWith: element, handler: nil)
        waitForExpectations(timeout: idleTime) { error in
            if (error != nil) {
                let message = "Failed to find \(element) after \(idleTime) seconds."
                self.recordFailure(withDescription: message, inFile: file, atLine: Int(line), expected: true)
            }
        }
    }
}

@aehlke

aehlke commented May 18, 2023

Copy link
Copy Markdown

how is this better than waitForExistence? is it faster?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment