Xcode UI Testing - typing text with typeText() method and autocorrection

Apan picture Apan · Sep 22, 2015 · Viewed 19.8k times · Source

I've got a test like below:

let navnTextField = app.textFields["First Name"]
let name = "Henrik"
navnTextField.tap()
navnTextField.typeText("Henrik")
XCTAssertEqual(navnTextField.value as? String, name)

Problem is that by default my iPhone Simulator has got Polish keyboard because of the system settings and "Henrik" is automatically changed into "ha" by autocorrect.

Simple solution is to remove Polish keyboard from the iOS Settings. This solution however is not solving the problem because iPhone Simulator can be reset and then test will fail again.

Is there any way to setup autocorrect before test case or other way to input text to text field.

Answer

mike picture mike · Jan 7, 2016

Here's a small extension on XCUIElement to accomplish this

extension XCUIElement {
    // The following is a workaround for inputting text in the 
    //simulator when the keyboard is hidden
    func setText(text: String, application: XCUIApplication) {
        UIPasteboard.generalPasteboard().string = text
        doubleTap()
        application.menuItems["Paste"].tap()
    }
}

It can be used like this

let app = XCUIApplication()
let enterNameTextField =  app.otherElements.textFields["Enter Name"]
enterNameTextField.tap()
enterNameTextField.setText("John Doe", app)
  • Credit goes to @Apan for the implementation