Swift2 UI测试 - 等待元素出现

时间:2015-12-02 16:29:11

标签: swift swift2 xcode-ui-testing

我希望暂停测试并等待元素出现在屏幕上,然后继续。

我没有看到为此创建期望并使用

等待的好方法
public func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?)

创建我一直在使用的期望的方法是

public func expectationForPredicate(predicate: NSPredicate, evaluatedWithObject object: AnyObject, handler: XCPredicateExpectationHandler?) -> XCTestExpectation

但是这需要一个已经存在的元素,而我想让测试等待一个尚不存在的元素。

有谁知道最好的方法吗?

6 个答案:

答案 0 :(得分:17)

expectationForPredicate(predicate: evaluatedWithObject: handler:)中,您不会提供实际对象,而是在视图层次结构中查找它。因此,例如,这是一个有效的测试:

let predicate = NSPredicate(format: "exists == 1")
let query = XCUIApplication().buttons["Button"]
expectationForPredicate(predicate, evaluatedWithObject: query, handler: nil)

waitForExpectationsWithTimeout(3, handler: nil)

查看标题中生成的UI Testing Cheat Sheetdocumentation(目前没有官方文档),全部由Joe Masilotti撰写。

答案 1 :(得分:4)

你可以在Swift 3中使用它

func wait(element: XCUIElement, duration: TimeInterval) {
  let predicate = NSPredicate(format: "exists == true")
  let _ = expectation(for: predicate, evaluatedWith: element, handler: nil)

  // We use a buffer here to avoid flakiness with Timer on CI
  waitForExpectations(timeout: duration + 0.5)
}

在Xcode 9,iOS 11中,您可以使用新的API waitForExistence

答案 2 :(得分:1)

它没有采用现有元素。您只需要定义以下谓词:

let exists = NSPredicate(format: "exists = 1")

然后在你的期望中使用这个谓词。当然,等待你的期望。

答案 3 :(得分:1)

对于Xcode 8.3及更高版本,您可以使用新类等待期望 - docs.size,示例测试如下所示:

XCTWaiter

Read the documentation了解更多信息。

答案 4 :(得分:0)

基于onmyway133 code,我想出了扩展(Swift 3.2):

extension XCTestCase {
  func wait(for element: XCUIElement, timeout: TimeInterval) {
    let p = NSPredicate(format: "exists == true")
    let e = expectation(for: p, evaluatedWith: element, handler: nil)
    wait(for: [e], timeout: timeout)
  }
}

extension XCUIApplication {
  func getElement(withIdentifier identifier: String) -> XCUIElement {
    return otherElements[identifier]
  }
}

因此,在您的呼叫网站上,您可以使用:

wait(for: app.getElement(withIdentifier: "ViewController"), timeout: 10)

答案 5 :(得分:0)

有人问这个问题有关Swift2的问题,但它仍然是2019年搜索量最高的结果,所以我想给出一个最新的答案。

使用Xcode 9.0+,由于waitForExistence,事情变得更简单了:

let app = XCUIApplication()
let myButton = app.buttons["My Button"]
XCTAssertTrue(myButton.waitForExistence(timeout: 10))
sleep(1)
myButton.tap()

WebViews示例:

let app = XCUIApplication()
let webViewsQuery = app.webViews
let myButton = webViewsQuery.staticTexts["My Button"]
XCTAssertTrue(myButton.waitForExistence(timeout: 10))
sleep(1)
myButton.tap()
相关问题