Swift 2 UI测试-等待元素出现

af7jpaap  于 2022-11-06  发布在  Swift
关注(0)|答案(6)|浏览(185)

我想让测试暂停,等待元素出现在屏幕上,然后再继续。
我看不出有什么好办法来创造一种期望,然后等待使用

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

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

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

但是这需要一个已经存在的元素,而我希望测试等待一个还不存在的元素。
有人知道最好的方法吗?

a5g8bdjr

a5g8bdjr1#

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测试备忘录和从标题生成的文档(目前还没有官方文档),所有这些都是由Joe Masilotti编写的。

5lwkijsr

5lwkijsr2#

这个问题是关于Swift2的,但它仍然是2019年的热门搜索结果,所以我想给予一个最新的答案。
Xcode 9.0+的waitForExistence让事情变得简单了一些:

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

Web视图示例:

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

xdyibdwo3#

你可以在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

holgip5t

holgip5t4#

它不接受已经存在的元素,只需要定义下面的 predicate :
let exists = NSPredicate(format: "exists = 1")
然后在你的期望中使用这个 predicate ,当然,等待你的期望。

anauzrmj

anauzrmj5#

对于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以获取更多信息。

ar7v8xwq

ar7v8xwq6#

基于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)

相关问题