Search code examples
swiftxctestxctestcase

typeText() is typing inconsistent characters


I'm beginning to dip my toes into Swift alongside writing UI tests and am having a problem with typing text into a textField. Below is the code:

func testLoginUsernameField() {
    let app = XCUIApplication()
    app.launch()

    let username = "testusername2"

    let usernameField = app.textFields["username_field"]
    XCTAssertTrue(usernameField.exists)

    usernameField.tap()
    usernameField.typeText(username)
    XCTAssertEqual(usernameField.value as! String, username)
}

The problem occurs when I do usernameField.typeText(username). My text continues to write tstusername2 rather than the testusername2.


Solution

  • This issue happens on the simulator when the Hardware Keyboard is enabled.

    Disable the hardware keyboard via the menu

    Go to I/O -> Keyboard -> Uncheck "Connect Hardware Keyboard" or use the shortcut ⇧⌘K.

    enter image description here

    Disable the hardware programmatically

    If you'd like to disable the hardware keyboard for your Scheme, no matter what simulator you run, refer to this StackOverflow post. I attempted to use other methods to disable the hardware keyboard via the App Delegate but had no luck.