【发布时间】:2016-09-23 15:28:56
【问题描述】:
我正在寻求帮助来编写一个等待指定元素不再出现在页面上的方法。我正在使用 Swift 2.2 和 XCTest 进行开发。如您所见,我是这里的新手,也是编程新手。非常感谢您的帮助。
【问题讨论】:
标签: swift xctest xcode-ui-testing xctestexpectation
我正在寻求帮助来编写一个等待指定元素不再出现在页面上的方法。我正在使用 Swift 2.2 和 XCTest 进行开发。如您所见,我是这里的新手,也是编程新手。非常感谢您的帮助。
【问题讨论】:
标签: swift xctest xcode-ui-testing xctestexpectation
您可以通过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")
}
【讨论】:
为此,我在XCUIElement 上写了一个超级简单的waitForNonExistence(timeout:) 扩展函数,它反映了现有的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
}
}
【讨论】:
您必须为要测试的条件设置谓词:
let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")
然后为您的测试用例中的谓词和 UI 元素创建一个期望:
self.expectationForPredicate(doesNotExistPredicate, evaluatedWithObject: element, handler: nil)
然后等待你的期望(指定超时,如果不满足期望,测试将失败,这里我使用5秒):
self.waitForExpectationsWithTimeout(5.0, handler: nil)
【讨论】: