2015-12-02 117 views
9

我想要暂停测试并等待元素出现在屏幕上,然后再继续。Swift2 UI测试 - 等待元素出现

我没有看到一个很好的方法来创建这样的一个期望和等待使用

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

的方法来创建我一直在使用已经

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

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

有没有人知道这样做的最好方法?

回答

15

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 Sheet,并从头部(有目前没有官方的文档),全部由乔Masilotti产生documentation

+1

谢谢大家! –

+0

我可以发誓我在早期版本的UI测试中尝试过这种方法,但它不起作用,哦,谢谢 – Alex

+0

此帮助程序也可以帮助http://masilotti.com/xctest-helpers/ – onmyway133

1

它不需要已经存在的元素。你只需要定义以下断言:

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

然后,只需使用此谓词在您的期望。当然,等待你的期望。

+0

我在Objective-C的例子,不迅速。如果你需要它,我可以包括它。 – sylvanaar

+0

这是一个正确的答案,谢谢! – Alex

3

你可以利用这一点,在斯威夫特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

0

有关的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我想出了以扩展(雨燕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)