# XCUITest

## 教學連結

* [**Waiting in XCTest**](http://masilotti.com/xctest-waiting/)

```swift
func waitForElementToAppear(_ element: XCUIElement) -> Bool {
    let predicate = NSPredicate(format: "exists == true")
    let expectation = expectation(for: predicate, evaluatedWith: element, 
                                  handler: nil)

    let result = XCTWaiter().wait(for: [expectation], timeout: 5)
    return result == .completed
}
```

```swift
func waitForElementToAppear(_ element: XCUIElement) -> Bool {
    let predicate = NSPredicate(format: "exists == true")
    let expectation = XCTNSPredicateExpectation(predicate: existsPredicate, 
                                                object: element)

    let result = XCTWaiter().wait(for: [expectation], timeout: 5)
    return result == .completed
}
```

* [**Asynchronous iOS Testing in Swift with XCWaiter**](https://medium.com/xcblog/asynchronous-ios-testing-in-swift-with-xcwaiter-e31c93014c33)
* [**UI Testing Cheat Sheet and Examples**](http://masilotti.com/ui-testing-cheat-sheet/)
* [**在 XCUITest 裡處理畫面捲動，直到目標元件出現**](https://jzchangmark.wordpress.com/2016/06/09/%E4%BD%BF%E7%94%A8-xctest-%E8%99%95%E7%90%86%E6%8D%B2%E5%8B%95%E7%95%AB%E9%9D%A2%E7%9B%B4%E5%88%B0%E6%9F%90%E5%85%83%E4%BB%B6%E5%87%BA%E7%8F%BE/)

```c
extension XCUIElement {
    func scrollToElement(element: XCUIElement, scroll:() -> Void) {
        while !element.visible() {
            scroll()
        }
    }

    func visible() -> Bool {
        guard self.exists && !CGRectIsEmpty(self.frame) else {
            return false
        }

        return CGRectIntersectsRect(XCUIApplication().windows.elementBoundByIndex(0).frame, self.frame)
    }
}
```

```c
func testScrollTable() {
    let app = XCUIApplication()
    let table = app.tables.elementBoundByIndex(0)
    let cell12 = table.cells.elementBoundByIndex(12)
    let mainWindow = XCUIApplication().windows.elementBoundByIndex(0)

    mainWindow.scrollToElement(cell20) {
        let fromPoint: XCUICoordinate = mainWindow.coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.75))
        let toPoint: XCUICoordinate = mainWindow.coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.25))

        fromPoint.pressForDuration(0, thenDragToCoordinate: toPoint)
    }
}
```

* [**inverted**](https://developer.apple.com/documentation/xctest/xctestexpectation/2806573-inverted?language=objc)

  ```
  Indicates that the expectation is not intended to happen.
  ```
