Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until object is not visible on the screen using Swift and XCTest

I'm looking for help writing a method which waits until the specified element is not present on a page anymore. I am developing with Swift 2.2 and XCTest. As you can see, I'm a new here and new to programming. Your help will be greatly appreciated.

like image 785
Vladimir Kamenev Avatar asked May 25 '16 20:05

Vladimir Kamenev


2 Answers

You will have to setup predicate for the condition you want to test:

let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")

Then create an expectation for your predicate and UI element in your test case:

self.expectationForPredicate(doesNotExistPredicate, evaluatedWithObject: element, handler: nil)

Then wait for your expectation (specifying a timeout after which the test will fail if the expectation is not met, here I use 5 seconds):

self.waitForExpectationsWithTimeout(5.0, handler: nil)
like image 168
Charles A. Avatar answered Sep 21 '22 15:09

Charles A.


I wrote a super simple waitForNonExistence(timeout:) extension function on XCUIElement for this which mirrors the existing XCUIElement.waitForExistence(timeout:) function, as follows:

extension XCUIElement {

    /**
     * Waits the specified amount of time for the element’s `exists` property to become `false`.
     *
     * - Parameter timeout: The amount of time to wait.
     * - Returns: `false` if the timeout expires without the element coming out of existence.
     */
    func waitForNonExistence(timeout: TimeInterval) -> Bool {
    
        let timeStart = Date().timeIntervalSince1970
    
        while (Date().timeIntervalSince1970 <= (timeStart + timeout)) {
            if !exists { return true }
        }
    
        return false
    }
}
like image 20
Adil Hussain Avatar answered Sep 20 '22 15:09

Adil Hussain