UI Test deleting text in text field

Tomasz Bąk picture Tomasz Bąk · Sep 28, 2015 · Viewed 39k times · Source

In my test I have a text field with a pre-existing text. I want to delete the content and type a new string.

let textField = app.textFields
textField.tap()
// delete "Old value"
textField.typeText("New value")

When deleting string with hardware keyboard Recording generated for me nothing. After doing the same with software keyboard I got:

let key = app.keys["Usuń"] // Polish name for the key
key.tap()
key.tap() 
... // x times

or

app.keys["Usuń"].pressForDuration(1.5)

I was worried that my test is language-dependent so I have created something like this for my supported languages:

extension XCUIElementQuery {
    var deleteKey: XCUIElement {
        get {
            // Polish name for the key
            if self["Usuń"].exists {
                return self["Usuń"]
            } else {
                return self["Delete"]
            }
        }
    }
}

It looks nicer in code:

app.keys.deleteKey.pressForDuration(1.5)

but it is very fragile. After quitting from Simulator Toggle software keyboard was reset and I've got a failing test. My solution doesn't work well with CI testing. How can this be solved to be more universal?

Answer

Bay Phillips picture Bay Phillips · Oct 1, 2015

I wrote an extension method to do this for me and it's pretty fast:

extension XCUIElement {
    /**
     Removes any current text in the field before typing in the new value
     - Parameter text: the text to enter into the field
     */
    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)
    }
}

This is then used pretty easily: app.textFields["Email"].clearAndEnterText("[email protected]")