Garrigan Stafford
Garrigan Stafford

Reputation: 1403

XCode UITest will not give NSTextField keyboard focus

So I have a window appear by clicking on a menu item. Normally the the first textBox would gain immediate keyboard focus, but in the UITest nothing in the window gains keyboard focus (no focus ring). This is problematic becuase it stops me from typing into the textfield with textField.typeText("someText")

I have tried .click() on the window and on the textbox to try and give it focus but nothing seems to bring the window or textbox in focus. Any help will be greatly appreciated

Example

MainMenu().menuItemForWindow.click() // Opens window
app.windows["windowTitle"].textFields["textBoxId"].click() // Clicks but field does not gain focus
app.windows["windowTitle"].textFields["textBoxId"].typeText("SomeText") // Is not typed into the textField

As a side note, I have verified that all the elements I am querying do actually exist.

EDIT:

I have gotten it to work by literally spamming typeText() until it changes the value of the given text box with something like

if let oldValue = textbox.value as? String {
   var newValue: String? = oldValue
   while newValue == oldValue {
         textbox.typeText("a")
         newValue = textbox.value as? String
   }
   //If we get here then we have edited the text box
   textbox.typeText(XCUIDeleteKey) // Get rid of spam text
   //TYpe what I want
   //...
 }

However this method is hacky and I can't really put a time out except from heuristics (roughly 15-30s) so I was hoping someone could help explain a better way of ensuring focus on the textbox or at least an explanation of what I am doing wrong originally. Any help would be greatly appreciated.

Upvotes: 2

Views: 530

Answers (1)

ablarg
ablarg

Reputation: 2490

Here are two possible ideas for you:

  1. Assign an Accessibility Id to the object you are trying to interact with, and try addressing it via the Accessibility Id. From https://blog.metova.com/guide-xcode-ui-test:

For element identification there is additionally elementMatchingPredicate(NSPredicate) and elementMatchingType(XCUIElementType, identifier: String?).

These are separate from containingPredicate(NSPredicate) and containingType(XCUIElementType, identifier: String?) which are checking the element for items inside it whereas the elementMatching... options are checking the values on the element itself. Finding the correct element will often include combinations of several query attributes.

  1. Enable Accessibility in the System Preferences | Accessibility as described here: https://support.apple.com/en-us/HT204434 and then send keyboard commands to set your focus.

Upvotes: 1

Related Questions