Swift UI测试 - 等待元素出现

问题描述 投票:9回答:5

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

我没有看到为此创建期望并等待使用的好方法

public func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?)

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

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

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

有谁知道最好的方法吗?

swift swift2 xcode-ui-testing
5个回答
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提供。


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


1
投票

它不需要已有的元素。您只需要定义以下谓词:

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

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


1
投票

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

func testExample() {
  let element = // ...
  let predicate = NSPredicate(format: "exists == true")
  let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)

  let result = XCTWaiter().wait(for: [expectation], timeout: 1)
  XCTAssertEqual(.completed, result)
}

Read the documentation了解更多信息。


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)
© www.soinside.com 2019 - 2024. All rights reserved.