One of my screen has multiple text fields, I can land to this screen from different other screens. In each case I am making one or another text field as first responder. I am not able to write test to determine whether the desired textField has focus or not.
When I print the textfield in console -
Output: { TextField 0x131171d40: traits: 146031247360, Focused, {{6.0, 108.3}, {402.0, 35.0}}, value: }
But I could not find any focus/isFocus property on XCUIElement.
Is there a way to achieve this ?
I don't know but maybe
selected
property onXCUIElement
is what you're looking for. Try it.Based on @hris.to's excellent answer, I put together this little extension (works in Swift 4 as well)...
I little bit late for the party :) However as far as I can see from dumping the variable XCUIElement it has one interesting property:
So you can check if your element has focus the following way:
NB: you can dump the property variables of any NSObject sublass with following extension:
Update: Properties dump, Swift 4:*
There is a method on
NSObject
via anextension
(fromUIAccessibility.h
), which is available onXCUIElement
namedaccessibilityElementIsFocused()
, but it seems to not returntrue
even when thedebugDescription
of that element clearly saysFocused
. There are a few other related methodsaccessibilityElementDidLoseFocus()
andaccessibilityElementDidBecomeFocused()
, which appear to be methods intended to be overridden by a subclasses ofNSObject
to get notified of changes to theFocused
state.After this digging I'm inclined to say that the notion of
Focused
that we are discussing is not the same as thefirstResponder
state, which is probably what you're hoping to know. I believe at this point that focus indicates that the element is the focus of some assistive technology likeVoiceOver
, based on some of the comments for these methods.If you want to be able to tell if an item is
firstResponder
directly, I think at this point it's time to file a bug report.If there is a way to interact directly with the software keyboard, a hacky workaround might be to get an
XCUIElement
for yourUITextField
and compare thevalue
of yourUITextField
element before and after typing with the keyboard (you may want to type a character then a backspace). Having said that, I could not figure out how to get the keyboard directly in a cursory attempt.I have observed some instances where
does not return true even when I had my cursor focussed on the text field but I was able to enter text with
.typeText()
. However,.enabled
correctly returns true , It appears 'enabled' value represents that UI element has accessibility enabled and you can interact with it.Not a clean solution but you can try,
or
.elementMatchingType()
to get XCUIElement and write your test block while handling the exception condition withguard
statement to throw appropriate error if the textField is not found.