3

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.

Bonteq
  • 777
  • 7
  • 24
  • How is SwiftUI an appropriate tag here? I see no SwiftUI in the question. – matt Mar 15 '20 at 00:50
  • Try deleting the `tap()`. – matt Mar 15 '20 at 00:51
  • Sorry about that. I deleted the SwiftUI tag. As for deleting tap(), this results in a `Neither element nor any descendant has keyboard focus` error. – Bonteq Mar 15 '20 at 01:21
  • OK darn, that didn't work. Okay, how about this; put back the `tap()` (obviously) and insert a 5-second pause before the `typeText` (I'm assuming you know how to do that). Does that help? – matt Mar 15 '20 at 01:32
  • Unfortunately, that doesn't work either. It's odd, it's still typing but it consistently misses the second character, regardless of the word, word length, sleep, etc. – Bonteq Mar 15 '20 at 01:46
  • Truly weird. Of course I can't reproduce the problem so I'm at a loss, sorry. – matt Mar 15 '20 at 01:49
  • Fair enough, I appreciate you trying to help. – Bonteq Mar 15 '20 at 01:53
  • 4
    How about if you write `for c in username {usernameField.typeText(String(c))}` ? – matt Mar 15 '20 at 01:57
  • That works! Definitely slows the test a bit, but it works as I'd hoped. Thank you. – Bonteq Mar 15 '20 at 02:04
  • 1
    Yeah, so what we've learned is it's missing a beat. I think this has something to do with the virtual keyboard. In my test, when I slowed it down, I saw the virtual keyboard rise up after the first letter had been typed. Try disabling the virtual keyboard and run the original test and see if that fixes it? – matt Mar 15 '20 at 02:14

1 Answers1

5

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.

Andre Yonadam
  • 964
  • 1
  • 13
  • 30