使用Swift和XCTest,等待对象在屏幕上不可见

8

我正在寻求帮助编写一种方法,直到页面上指定的元素不再存在时等待。我正在使用Swift 2.2和XCTest进行开发。正如您所看到的,我是新手,并且对编程也很陌生。非常感谢您的帮助。

4个回答

18

您需要设置一个谓词来测试您想要测试的条件:

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

然后在您的测试用例中为谓词和UI元素创建一个期望值:

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

然后等待您的期望值(在指定的超时时间后,如果未满足期望,则测试将失败,这里我使用5秒):

self.waitForExpectationsWithTimeout(5.0, handler: nil)

7
我为此编写了一个非常简单的waitForNonExistence(timeout:)扩展函数,它基于XCUIElement,并镜像了现有的XCUIElement.waitForExistence(timeout:)函数。
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
    }
}

1

@Charles A 的回答是正确的。以下是同样功能的 Swift 5 版本。

        let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")
    expectation(for: doesNotExistPredicate, evaluatedWith: element, handler: nil)
    waitForExpectations(timeout: 5.0, handler: nil)

0

您可以通过XCUIElement.exists每秒检查10秒钟来检查元素,然后断言该元素。以下是ActivityIndicator的示例:

public func waitActivityIndicator() {
    var numberTry = 0
    var activityIndicatorNotVisible = false
    while numberTry < 10 {
        if activityIdentifier.exists {
            sleep(1)
            numberTry += 1
        } else {
            activityIndicatorNotVisible = true
            break
        }
    }
    
    XCTAssert(activityIndicatorNotVisible, "Activity indicator is still visible")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接