UITesting in iOS: tap() method doesn't work properly - ios

I am facing a strange problem with UITesting in Swift under iOS 10.3.2 and Xcode 8.3.3 .
I am running a simple test inside my app which should tap and verify every single row inside a TableView (is the Settings view of my application so every single row is loaded from the disk and nothing is downloaded from the web at this step), but for a strange reason when I tap on a row which previously wasn't visible the .tap() method doesn't work.
Example Code:
let app = XCUIApplication()
let myTableView = app.tables.element(matching: .table, identifier: "tableView01")
myTableView.swipeUp(). //I swipe so that the cell becomes visible...
let myCell = myTableView.cells.element(matching: .cell, identifier: "tappableCell")
myCell.tap()
The strange thing is that I have a correct output from the console in Xcode.
t = 328.24s Tap "tappableCell" Cell
t = 328.24s Wait for app to idle
t = 328.80s Find the "tappableCell" Cell
t = 328.80s Snapshot accessibility hierarchy for com.thefloow.enterprise.ownbrand
t = 328.92s Find: Descendants matching type Table
t = 328.92s Find: Element at index 0
t = 328.92s Find: Descendants matching type Cell
t = 328.92s Find: Elements matching predicate '"tappableCell" IN identifiers'
t = 329.04s Wait for app to idle
t = 329.22s Synthesize event
t = 329.37s Wait for app to idle
Another strange thing is that if I put a breakpoint before the tap method and then I run it from the command line it works perfectly giving me the same output from the console.
What could be the reason of this strange behaviour?
Thank you for your help!
Andrea

I found that the problem is in the framework. After scrolling the UI doesn't respond properly so I had to double tap on the cell to resign the UIResponder and then the test works properly. I've also reported the issue to  to know if it is a regular behaviour or not.
However thank you to everyone! Happy coding!

Related

UITest keeps failing to tap alert view when running on simulator

I have created a series of UI Tests that run fine on a device but when using a Simulator, I cannot tap alert view buttons.
let alert = app.alerts["Continue"]
alert.buttons["Yes"].tap()
Instead, it crashes with
Find: Descendants matching type Button
t = 10.17s Find: Elements matching predicate '"Yes" IN identifiers'
t = 10.18s Check for interrupting elements affecting "Yes" Button
t = 10.19s Requesting snapshot of accessibility hierarchy for app with pid 14120
t = 10.21s Find: Descendants matching predicate identifier == "NotificationShortLookView" OR elementType == 7
*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil (NSInvalidArgumentException)
I believe (and hope) this is an Xcode 13 bug and may be fixed in an update soon.
Does any one know a way around this?
Turns out this is only an issue when running on an iOS 12 simulator. It is ok when running on an iOS 15.4 simulator.

Item Selection handler not working on Iphone 6 - iOS 11 ( pod SearchTextField )

I am trying to make a Autocomplete TextField with drop down.In android there is very handy and beautiful Autocomplete widget. But Sadly I did not found any here iOS.
So I tried this library. It is so easy to use and it looks good with UI. But there is a problem, and that Is when I search any Item and that got list in dropdown, I am unable to select any of them.The code goes like this:
myTextField.itemSelectionHandler = { filteredResults, itemPosition in
// Just in case you need the item position
let item = filteredResults[itemPosition]
print("Item at position \(itemPosition): \(item.title)")
// Do whatever you want with the picked item
self.myTextField.text = item.title
}
I am working on project and just included it. But it is really not getting called. Do you experienced same issue? and how to fix it ?
Two common things to forget if you are not an experienced iOS dev are:
Connecting the input to your viewcontroller via an outlet (https://youtu.be/G_JKLxPYd60?t=208)
Specifying the custom class of the input in the storyboard
I added 2 screenshots to show you what I mean.
I have created a small example project to hopefully help you out.

Xcode UI Tests Multiple Buttons Found

I'm having a problem where my UI Test says multiple buttons found when using the following code.
app.buttons["Upgrade"].tap()
So I reran my unit test and set a breakpoint right before running that line and hit the record button and clicked the button and it generated the following code.
app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).buttons["Upgrade"].tap()
Of course at the top of the test I have let app = XCUIApplication().
Any idea why this would be happening?
Sometimes when running p UIApplication.shared.windows in the debugger it has 2 values in the array. I'm not sure why as I never have multiple windows. The only interactions I have with windows is setting UIApplication.shared.keyWindow?.rootViewController to different view controllers sometimes, and the following code in didFinishLaunchingWithOptions.
// Get view controllers ready
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController: ViewController = mainStoryboard.instantiateViewController(withIdentifier: "FirstView") as! ViewController
// Show view controller
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
That is within an if statement and within the else statement I have pretty much the same code except instead of FirstView it's SecondView.
This message appears because there is more than one button on the screen with the accessibilityIdentifier, accessibilityLabel or value, "Upgrade", so it can't work out which one to tap.
The reason that it works when you use the recorded version is because the recording tool has identified that the search needs to be narrowed down to search inside the element of type .other at index 1, in order to be sure of which "Upgrade" button to interact with.
It's not a problem with your window(s), but with the uniqueness of your buttons' identifiers, and how you're handling them in your test.
In a situation where the button is only used once on the page of your app in question, it's best to set a unique accessibilityIdentifier on the UIButton. Its value should be unique within that page of your app, so make sure you aren't using the same string anywhere else. Then you can access the button unambiguously:
// app code
let upgradeButton: UIButton!
upgradeButton.accessibilityIdentifier = "upgradeButton"
// test code
let app = XCUIApplication()
let upgradeButton = app.buttons["upgradeButton"]
upgradeButton.tap()
In the situation where there are multiple instances of the same upgrade button on screen at the same time (e.g. where the button is part of a repeated pattern on the screen, like if there are lots of products for sale), it's OK for them each to have the same accessibilityIdentifier, but you should change the way you access the element in your test, using element(boundBy:) to access items at specified indices:
// app code
let upgradeButton: UIButton!
upgradeButton.accessibilityIdentifier = "upgradeButton"
// test code
let app = XCUIApplication()
let upgradeButton = app.buttons["upgradeButton"].element(boundBy: 1) // second upgrade button
upgradeButton.tap()
In this situation, you could also take the approach of finding the correct container view, and searching for the upgrade button inside it.
// test code
let app = XCUIApplication()
let upgradeButtonContainer = app.descendants(matching: .any).containing(.button, identifier: "upgradeButton").element(boundBy: 1) // second upgrade button-containing element
let upgradeButton = upgradeButtonContainer.buttons["upgradeButton"]
upgradeButton.tap()
I faced same issue and tried multiple things to get out of it. Ultimately i found out out that the issue started happening when i updated my Xcode to 8.3.3 and simulator os to iOS 10.3.
Switched my simulator os back to iOS 10.2 and it worked perfectly.
I am seeing similar problems since updating to Xcode 8.3 where the XCUIElementQuery is returning multiple results when there should be only one. There may be a bug introduced in this build.
https://forums.developer.apple.com/thread/75546
describes the bug and the radar is here:
https://openradar.appspot.com/31498932
I've tried the posted workaround by trying to coerce my queries to return the desired object as an XCUIElementQuery and then using element(boundBy:) and it worked for me.
It's upsetting how unstable the UI Tests are.

iOS 9 Segue Causes App To Freeze (no crash or error thrown)

I have been working on this app for months now and from as far back as I can remember I have never had an issue with segues. The code is unchanged in terms of calling performSegueWithIdentifier but since my recent update to Xcode 7 and iOS 9 I have not been able to tack this issue.
I have tried:
Deleting button and creating new button w/ segue link
Using a direct segue from button to view, without the use of performSegueWithIdentifier
Connecting button to new blank viewController
When I press the button, no initial load functions are called on the destination VC (Ex: ViewDidLoad, ViewWillAppear, etc). When I connect it to a blank view, the segue works fine with the same code in place.
Since the code never stops, or breaks, and just seems to "freeze" in place while still running on Xcode I can't seem to even narrow this down to whats causing the issue. I have a similar segue that is also called from another button on the same ViewController that has no issues whatsoever.
Any thoughts on the matter are greatly appreciated!
EDIT: I have narrowed the issue down to the UITextView's causing the problem. Once the Text Views were removed the page loads fine via segue. I wonder what changed between iOS 8 and iOS 9 in terms of UITextView as I will have to remove the text views and completely re add new text views.
So basically the segue was freezing because of the UITextView's I was using in the destinationViewController. The following fixed the issue:
Delete all UITextView's
Add new UITextView's
you must leave the default lorem imposed text and change this programmatically in the viewDidLoad()
This was the fix for me, and from the research I have done on the issue it seems this is a bug in iOS 9 and Xcode 7.
Cheers!
NOTE: Removing the text in the UITextView (or making it longer then ~12 characters) is sufficient to work around it, no need to delete and recreate them. This is fixed in Xcode 7.1.1 and later.
I ran into the same issue and the fixes in this post (Xcode 7 crash: [NSLocalizableString length] 30000) solved the issue for me.
The first is to enable a localisation other than the base for the storyboard (see https://stackoverflow.com/a/32688815/3718974)
The second is to turn off the base localisation (see https://stackoverflow.com/a/32719247/3718974)
I think I have the same problem: I have a UITabelView with cells created from a nib file, when a user tap a cell this method is called:
and when I have the following method prepareForSegue:: the application crashes:
if I delete the line 129 Everything is ok , the method prepareForSegue:: open the right view and the label contactName is shown with its default text.
If I modify the method as follows prepareForSegue:: get exactly what you expect, without having any type of error:
let me know if you also get the same result
Any one who is facing this issue, i solved it by turning off the "Optimize rendering for windows scale" option in Debug of simulator window. I already had tried all of the above answers but could not solve the issue.
In the method in the first viewController where you activate the segue, do you have beginIgnoringInteractionEvents anywhere? If so the screen you segue to will be frozen and will ignore interaction events like you describe. If this is the case you can fix this by adding an endIgnoringInteractionEvents method before your segue method:
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.performSegueWithIdentifier("editItemToMyGearSegue", sender: self)
I realize this is an old topic, but appears to be still relevant. I was facing the same problem in Xcode 9, iOS11. My UITextViews are embedded inside UITableViewCells. Same symptoms as described here. The tricks with default text and placeholders did nothing for me, but I solved it by turning off the scrolling indicators for the text view in the xib. They were on by default, I guess, though unused.
Edit: this is probably an important detail... the views that were hanging all had an image NSTextAttachment in the attributed string of the text view. I think the image was wider than the available table cell content. With scrolling turned off, they appear to downscale.

UI Testing Failure - Neither element nor any descendant has keyboard focus on secureTextField

This is my case:
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText("wrong_password") //here is an error
UI Testing Failure - Neither element nor any descendant has keyboard focus. Element:
What is wrong? This is working nice for normal textFields, but problem arise only with secureTextFields. Any workarounds?
This issue caused me a world of pain, but I've managed to figure out a proper solution. In the Simulator, make sure I/O -> Keyboard -> Connect hardware keyboard is off.
Recently we found a hack to make solution from accepted answer persistent. To disable Simulator setting: I/O -> Keyboard -> Connect hardware keyboard from command line one should write:
defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0
It will not affect a simulator which is running - you need to restart simulator or start a new one to make that setting have its effect.
I have written a small extension (Swift) which works perfect for me.
Here is the code:
extension XCTestCase {
func tapElementAndWaitForKeyboardToAppear(element: XCUIElement) {
let keyboard = XCUIApplication().keyboards.element
while (true) {
element.tap()
if keyboard.exists {
break;
}
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
}
}
}
The main idea is to keep tapping an element (text field) before the keyboard is presented.
Stanislav has the right idea.
In a team environment, you need something that will automatically work. I've come up with a fix here on my blog.
Basically you just paste:
UIPasteboard.generalPasteboard().string = "Their password"
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.pressForDuration(1.1)
app.menuItems["Paste"].tap()
Another cause of this error is if there is a parent view of the text field in which you are trying to enter text that is set as an accessibility element (view.isAccessibilityElement = true). In this case, XCTest is not able to get a handle on the subview to enter the text and returns the error.
UI Testing Failure - Neither element nor any descendant has keyboard
focus.
It isn't that no element has focus (as you can often see the keyboard up and blinking cursor in the UITextField), it is just that no element it can reach has focus. I ran into this when attempting to enter text in a UISearchBar. The search bar itself is not the text field, when setting it as an accessibility element, access to the underlying UITextField was blocked. To resolve this, searchBar.accessibilityIdentifier = "My Identifier" was set on the UISearchBar however the isAccessibilityElement was not set to true. After this, test code of the form:
app.otherElements["My Identifier"].tap()
app.otherElements["My Identifier"].typeText("sample text")
Works
It occurred with me for many times.
You have to disable Keyboard Hardware and Same Layout as OSX in your Simulator
Hardware/Keyboard (disable all)
After that keyboard software won't dismiss and your tests can type text
In my case this Hardware -> Keyboard -> Connect Hardware Keyboard -> Disable didn't worked for me.
But when I followed
1) Hardware -> Keyboard -> Connect Hardware Keyboard -> Enabled and run the app
2) Hardware -> Keyboard -> Connect Hardware Keyboard -> Disable.
It worked for me
func pasteTextFieldText(app:XCUIApplication, element:XCUIElement, value:String, clearText:Bool) {
// Get the password into the pasteboard buffer
UIPasteboard.generalPasteboard().string = value
// Bring up the popup menu on the password field
element.tap()
if clearText {
element.buttons["Clear text"].tap()
}
element.doubleTap()
// Tap the Paste button to input the password
app.menuItems["Paste"].tap()
}
Use a sleep between launching the app and typing in data in textfields like this:
sleep(2)
In my case I was keeping getting this error every time and only this solution helped my out.
This maybe help: I just add a "tap" action before the error; that´s all :)
[app.textFields[#"theTitle"] tap];
[app.textFields[#"theTitle"] typeText:#"kk"];
Record case however you want, keyboard or without keyboard attached.
But do the following before playing test.
This following option (connect hardware keyboard) should be unchecked while playing test.
[Reposting Bartłomiej Semańczyk's comment as an answer because it solved the problem for me]
I needed to do Simulator > Reset Contents and Settings in the simulator menu bar to make this start working for me.
Works for me:
extension XCUIElement {
func typeTextAlt(_ text: String) {
// Solution for `Neither element nor any descendant has keyboard focus.`
if !(self.value(forKey: "hasKeyboardFocus") as? Bool ?? false) {
XCUIDevice.shared.press(XCUIDevice.Button.home)
XCUIApplication().activate()
}
self.typeText(text)
}
}
I ran into this issue and was able to fix it in my scenario by taking the solution posted by #AlexDenisov and adding it to my pre-actions for run & test.
The above answers solved it for me when running UI tests while the simulator UI is in the foreground (when you could see the changes in the simulator window). However, it did not work when running them in the background (which is how fastlane ran them, for example).
I had to go to Simulator > Device > Erase All Content and Settings...
To be clear, I manually disabled-enabled-disabled the Hardware Keyboard in the Simulator Settings, set defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0, and then erased content and settings.
Sometime text fields are not implemented as text fields, or they're wrapped into another UI element and not easily accessible.
Here's a work around:
//XCUIApplication().scrollViews.otherElements.staticTexts["Email"] the locator for the element
RegistrationScreenStep1of2.emailTextField.tap()
let keys = app.keys
keys["p"].tap() //type the keys that you need
//If you stored your data somewhere and need to access that string //you can cats your string to an array and then pass the index //number to key[]
let newUserEmail = Array(newPatient.email())
let password = Array(newPatient.password)
//When you cast your string to an array the elements of the array //are Character so you would need to cast them into string otherwise //Xcode will compain.
let keys = app.keys
keys[String(newUserEmail[0])].tap()
keys[String(newUserEmail[1])].tap()
keys[String(newUserEmail[2])].tap()
keys[String(newUserEmail[3])].tap()
keys[String(newUserEmail[4])].tap()
keys[String(newUserEmail[5])].tap()
The following is from a Swift 5.4, SwiftUI app scenario which would fail UI Testing.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :FAIL:
Test: Failed to synthesize event: Neither element nor any descendant has keyboard focus.
Solution: Tap Again
A second tap() was found to pass.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
However, .doubleTap() and tap(withNumberOfTaps: 2, numberOfTouches: 1) would still fail.
Solution: Await TextField Arrival, Then Tap
Sometimes a view transition needs to expressly await the TextEdit arrival. The approach below awaits the arrival of the targeted TextEdit field.
XCTestCase.swift extension:
extension XCTestCase {
func awaitArrival(element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 1")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
func awaitDeparture(element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 0")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
}
Example use:
app.cells.firstMatch.tap()
// transition from list view to detail view for item
awaitArrival(
element: app.textFields.matching(identifier: "balance_textedit").element,
timeout: 5)
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
Solution: waitForExistence, Then Tap
Use the waitForExistence(timeout:) method provided by XCUIElement.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields.matching(identifier: "balance_textedit")
.element.waitForExistence(timeout: 5)
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
Your first line is just a query definition, which doesn't mean that passwordSecureTextField would actually exist.
Your second line will dynamically execute the query and try to (re)bind the query to UI element. You should put a breakpoint on it and verify that one and only one element is found. Or just use an assert:
XCTAssertFalse(passwordSecureTextField.exists);
Otherwise it looks ok, tap should force keyboard visible and then typeText should just work. Error log should tell you more info.
Don't messed up, There problem caught the reason is you are recorded your testing time your app will connection hardware keyboard while your automatic testing time simulator takes only software keyboard. so for how to fix this issues. Just use software keyboard on your recording time. you can see the magic.
We encountered the same error when setting the accessibilityIdentifier value for a custom view (UIStackView subclass) containing UIControl subviews. In that case XCTest was unable to get the keyboard focus for the descendent elements.
Our solution was simply to remove the accessibilityIdentifier from our parent view and set the accessibilityIdentifier for the subviews through dedicated properties.
Another answer, but for us the problem was the view was too close to another view that a Gesture recognizer on it. We found we needed the view to be at least 20 pixels away (in our case below). Literally 15 didn't work and 20 or more did. This is strange I'll admit, but we had some UITextViews that were working and some that were not and all were under the same parent and identical other positioning (and variable names of course). The keyboard on or off or whatever made no difference. Accessibility showed the fields. We restarted our computers. We did clean builds. Fresh source checkouts.
No Need to turn on/off keyboard in I/O.
Don't use .typeText for secureTextField, just use
app.keys["p"].tap()
app.keys["a"].tap()
app.keys["s"].tap()
app.keys["s"].tap()
Bonus: You get keyboard sound click :)
Finally, I wrote a script which edits the Simulator's .plist file and sets the ConnectHardwareKeyboard property to false for the selected simulator. You heard it right, it changes the property for the specifically selected simulator inside "DevicePreferences" dictionary rather than editing the global property.
First, create a shell script named disable-hardware-keyboard.sh with the following contents. You can place it within "YourProject/xyzUITests/Scripts/".:
echo "Script: Set ConnectHardwareKeyboard to false for given Simulator UDID"
if [[ $1 != *-*-*-*-* ]]; then
echo "Pass device udid as first argument."
exit 1
else
DEVICE_ID=$1
fi
DEVICE_PREFERENCES_VALUE='<dict><key>ConnectHardwareKeyboard</key><false/></dict>'
killall Simulator # kill restart the simulator to make the plist changes picked up
defaults write com.apple.iphonesimulator DevicePreferences -dict-add $DEVICE_ID $DEVICE_PREFERENCES_VALUE
open -a Simulator # IMPORTANT
Now follow these steps to call it with passing the selected simulator's udid as an argument:
Edit your Xcode scheme (or UI tests specific scheme if you have one)
Go to: Test > Pre-actions
Add new script by tapping "+" symbol > "New Run Script Action".
Important: Inside "Provide build settings from" dropdown choose your main app target, not the UI tests target.
Now add the following script in the text area below.
Script inside Test>Pre-actions:
#!/bin/sh
# $PROJECT_DIR is path to your source project. This is provided when we select "Provide build settings from" to "AppTarget"
# $TARGET_DEVICE_IDENTIFIER is the UDID of the selected simulator
sh $PROJECT_DIR/xyzUITests/Scripts/disable-hardware-keyboard.sh $TARGET_DEVICE_IDENTIFIER
# In order to see output of above script, append following with it:
# | tee ~/Desktop/ui-test-scheme-prescript.txt
Time to test it:
Launch simulator
Enable hardware keyboard for it
Run any UI test with keyboard interaction. Observe the simulator restarts and the hardware keyboard is disabled. And the test's keyboard interaction is working fine. :)
Long story short: hardware keyboard input in iOS Simulator seems to broken for a long time.
The thing is that -[UIApplicationSupport _accessibilityHardwareKeyboardActive] private method from com.apple.UIKit.axbundle sometimes returns NO even though it should return YES (when a text input view is firstResponder, and the cursor is blinking, which literally means that the hardware keyboard is active).
Put this code anywhere in the app to make iOS Simulator believe that if Software Keyboard is inactive then the hardware one is active.
#if TARGET_OS_SIMULATOR
__attribute__((constructor))
static void Fix_UIApplicationAccessibility__accessibilityHardwareKeyboardActive(void) {
{
static id observer = nil;
observer = [[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
NSBundle *bundle = note.object;
if ([bundle.bundleIdentifier isEqualToString:#"com.apple.UIKit.axbundle"]) {
Class cls = objc_lookUpClass("UIApplicationAccessibility");
SEL sel = sel_getUid("_accessibilityHardwareKeyboardActive");
Method m = class_getInstanceMethod(cls, sel);
method_setImplementation(m, imp_implementationWithBlock(^BOOL(UIApplication *app) {
return ![[app valueForKey:#"_accessibilitySoftwareKeyboardActive"] boolValue];
}));
}
}];
}
}
#endif
emailTextField.tap() // add this line before typeText
emailTextField.typeText("your text")
The problem for me was the same as for Ted. Actually if password field gets tapped after login field and hardware KB is on, software keyboard will dismiss itself on second field tap, and it's not specific to UI tests.
After some time messing around with AppleScript, here's what I came up with(improvements are welcome):
tell application "Simulator"
activate
tell application "System Events"
try
tell process "Simulator"
tell menu bar 1
tell menu bar item "Hardware"
tell menu "Hardware"
tell menu item "Keyboard"
tell menu "Keyboard"
set menuItem to menu item "Connect Hardware Keyboard"
tell menu item "Connect Hardware Keyboard"
set checkboxStatus to value of attribute "AXMenuItemMarkChar" of menuItem
if checkboxStatus is equal to "✓" then
click
end if
end tell
end tell
end tell
end tell
end tell
end tell
end tell
on error
tell application "System Preferences"
activate
set securityPane to pane id "com.apple.preference.security"
tell securityPane to reveal anchor "Privacy_Accessibility"
display dialog "Xcode needs Universal access to disable hardware keyboard during tests(otherwise tests may fail because of focus issues)"
end tell
end try
end tell
end tell
Create a script file with code above and add it to necessary targets(probably UI tests target only, you may want to add similar script to your development targets to re-enable HW keyboard during development).
You should add Run Script phase in build phases and use it like this:
osascript Path/To/Script/script_name.applescript
Had the same issue with Securetextfields. The connect hardware option in my Simulator was of, but still ran into the issue. Finally, this worked for me (Swift 3):
let enterPasswordSecureTextField = app.secureTextFields["Enter Password"]
enterPasswordSecureTextField.tap()
enterPasswordSecureTextField.typeText("12345678")
What fixed this problem for me was adding a 1 second sleep:
let textField = app.textFields["identifier"]
textField.tap()
sleep(1)
textField.typeText(text)

Resources