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

ios9uitextfieldxcode-ui-testingxctest

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.

Best Answer

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
Related Topic