2015-12-02 110 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)