Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - UI Test deleting text in text field

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...