How to handle alert in UITests in iOS

Issue #82

Usually in an app, you have the onboarding with steps that require push notification and location permission to be turned on. And you want to automate these steps via UITests

Firstly, you need to add interruption handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
addUIInterruptionMonitor(withDescription: "Alert") {
element in
do {
// Push Notification
let button = element.buttons["Allow"]
let title = element.staticTexts["“MyAwesomeApp” Would Like to Send You Notifications"]
if title.exists && button.exists {
button.tap()
}
}

do {
// Location
let button = element.buttons["Only While Using the App"]
if button.exists {
button.tap()
}
}

return true
}
}

Then you need to call tap on XCUIApplication to make the app responsive

1
2
turnOnPushNotificationButton.tap()
tap()

Sometimes the alert handling is slow and you get Did not receive view did disappear notification within 2.0s. Well, the workaround is to wait for the element on next onboarding step to appear. Starting with Xcode 9, you can use waitForExistence.

This is how you can go to last step after user has enabled push notification

1
2
let label = staticTexts["Congratulation. You've granted us permission. Now enjoy the app."]
_ = label.waitForExistence(timeout: 5)

Comments