Search code examples
iosxctestxcode-ui-testingxcode9-betaxcode9

Xcode 9: How to create XCUIElement instances using XCUIElementQuery?


After watching the 2017 WWDC Xcode and XCTest videos, I updated my tests to use latest additions in XCTests.

I recently upgraded to Xcode 9 Beta, runnning OS X Sierra 10.12.4

After this, all tests where I used XCUIElement() to create an element instance, failed.

Example code line: XCTAssertTrue(XCUIElement().scrollToElement(tablesQuery.cells.staticTexts["Featured"]).exists)

This is the error I get: 'init()' is unavailable: Use XCUIElementQuery to create XCUIElement instances.

If you are curious what scrollToElement() is, it is a custom function to scroll to the element being queried, if it is not visible in current view. It is part of a custom extension of XCUIElement I wrote.

As part of solution, can you suggest: How XCUIElement instances are expected to be created now?

For reference: scrollToElement()

open func scrollToElement(_ element: XCUIElement) -> XCUIElement {
    while !element.visible() {
        swipeUp()
    }
    return element
}

open func visible() -> Bool {
    guard self.exists && !self.frame.isEmpty else { return false }
    return XCUIApplication().windows.element(boundBy: 0).frame.contains(self.frame)
}

Any help is appreciated!


Solution

  • You cannot initialize XCUIElements directly - you must access them through XCUIApplication, which is a subclass of XCUIElement. If you call your scrolling method from XCUIApplication, it will work.

    let app = XCUIApplication()
    XCTAssertTrue(app.scrollToElement(app.tables.cells.staticTexts["Featured"]).exists)