Stephen
Stephen

Reputation: 161

Xcode 7 UI Testing - can't type text into search bar

The following UI Test code will successfully tap the UISearchBar element. The software keyboard appears and the search bar looks like it has focus. (ie. it animates as if someone tapped it)

let searchBar = XCUIApplication().otherElements["accessibility_label"]
searchBar.tap()
searchBar.typeText("search text")

However, typeText fails with:

UI Testing Failure - Neither element nor any descendant has keyboard focus. Element:

Note: Hardware->Keyboard->Connect Hardware Keyboard is toggled off. This solved the same issue for text fields but the search bar is still failing.

Upvotes: 16

Views: 9419

Answers (5)

J. Fdez
J. Fdez

Reputation: 156

I use the following (Swift 4, Xcode 9.4.1):

app.searchFields["Placeholder"].clearAndEnterText("String to search")
app.buttons["Search"].tap()

... where "Placeholder" is the string that appears in the textfield before typing the text.

Note: clearAndEnterText is a function created in a XCUIElement extension:

    func clearAndEnterText(_ text: String)
    {
        guard let stringValue = self.value as? String else {
            XCTFail("Tried to clear and enter text into a non string value")
            return
        }

        self.tap()

        let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: stringValue.count)

        self.typeText(deleteString)
        self.typeText(text)
    }

Hope this can help you.

Upvotes: 2

Tobe
Tobe

Reputation: 518

it worked for me to set

searchBar.accessibilityTraits = UIAccessibilityTraitSearchField

in the view controller and then access it in the UI test by

let searchfield = app.searchFields.element(boundBy: 0) 
searchfield.typeText("foobar")

Upvotes: 5

Kushal Jogi
Kushal Jogi

Reputation: 285

Just put a wait for few seconds and it will work!

let searchBar = XCUIApplication().otherElements["accessibility_label"]
searchBar.tap()
sleep(5)
searchBar.typeText("search text")

Upvotes: -1

rudald
rudald

Reputation: 404

I found something:

let app = XCUIApplication()
app.tables.searchFields["Search"].tap()
app.searchFields["Search"].typeText("something")

It looks strange, but it works for me.

Upvotes: 14

Koraktor
Koraktor

Reputation: 42913

I used the following workaround successfully:

let firstCell = app.cells.elementBoundByIndex(0)
let start = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 0))
let finish = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 3))
start.pressForDuration(0, thenDragToCoordinate: finish)

app.searchFields.element.tap()
app.searchFields.element.typeText("search text")

This effectively scrolls the search bar into view and taps it to focus, after that typeText() can be used.

Upvotes: 3

Related Questions