Interactions and Assertions
On this page
Finding an element is half of a test. The other half is doing something to it and checking that the app reacted. This chapter covers the gestures and keyboard input XCUITest offers, what you can read back from an element, and how to write assertions whose failure messages tell you what went wrong.
Gestures#
Every XCUIElement has methods that synthesize real touch events at the element's hit point (by default its centre):
| Method | Use |
|---|---|
tap(), doubleTap()
|
buttons, rows, fields |
press(forDuration:) |
long press, context menus |
press(forDuration:thenDragTo:) |
drag and drop, reordering |
swipeLeft(), swipeRight(), swipeUp(), swipeDown()
|
swipe actions, scrolling, paging |
pinch(withScale:velocity:), rotate(_:withVelocity:)
|
maps, images |
adjust(toPickerWheelValue:), adjust(toNormalizedSliderPosition:)
|
pickers and sliders |
Before each gesture XCUITest waits for the app to be idle, scrolls the element into view if it sits in a scroll view, and checks that it is hittable. If another view covers it, the gesture fails rather than tapping the wrong thing. Chapter 4 shows a real case of that.
When you need a point rather than an element, for example the empty area of a canvas, use coordinates relative to an element:
let canvas = app.otherElements["drawing.canvas"]
canvas.coordinate(withNormalizedOffset: CGVector(dx: 0.25, dy: 0.5)).tap()
Use this sparingly. A coordinate tap ignores what is actually at that point, so it is the first thing to break on a different screen size.
Typing#
typeText(_:) types into the element that has keyboard focus. Tap the field first:
let newTitle = app.textFields["tasks.newTitle"]
newTitle.tap()
newTitle.typeText("Water the plants")
If the element you call typeText on does not have focus, the call fails with "Neither element nor any descendant has keyboard focus". The usual causes: the tap was missing, the tap landed on something covering the field, or focus moved to another field.
A few keyboard facts that save time:
- Typing
"\n"presses Return, which submits a field that has anonSubmithandler. - To clear a field, tap it and type
XCUIKeyboardKey.delete.rawValuerepeated as many times as the value is long. There is noclearText()method. - Simulators type through a connected hardware keyboard when one is enabled (I/O > Keyboard > Connect Hardware Keyboard), so the on-screen keyboard may not appear.
typeTextworks either way, but do not assert onapp.keyboardsexisting.
Reading state back#
What a test can read from an element is what accessibility exposes:
-
exists: is there a match right now. It does not wait. -
isHittable: exists, is on screen and can receive a tap. -
isEnabled,isSelected: control state. -
label: the accessibility label, usually the visible text. -
value:Any?, the accessibility value. For a text field it is the text, for a switch"1"/"0", for a slider a percentage, and for the Tasks rows"open"or"done"because the app setsaccessibilityValue. -
placeholderValue,identifier,frame,elementType.
One quirk you will meet with SwiftUI text fields: when the field is empty, value returns the placeholder text, not an empty string. That is what the assertion on the cleared field below checks.
A complete interaction test#
TaskFlowTests.swift adds a task, ticks it off and deletes it, checking each step:
import XCTest
final class TaskFlowTests: XCTestCase {
let app = XCUIApplication()
override func setUpWithError() throws {
continueAfterFailure = false
app.launchArguments = ["-resetState"]
app.launchEnvironment = ["UITEST_SKIP_LOGIN": "1"]
app.launch()
}
func testAddCompleteAndDeleteATask() throws {
let newTitle = app.textFields["tasks.newTitle"]
let add = app.buttons["tasks.add"]
let count = app.staticTexts["tasks.count"]
XCTAssertFalse(add.isEnabled, "Add must be disabled while the field is empty")
newTitle.tap()
newTitle.typeText("Water the plants")
XCTAssertTrue(add.isEnabled)
add.tap()
let row = app.buttons["Water the plants"]
XCTAssertTrue(row.exists)
XCTAssertEqual(row.value as? String, "open")
XCTAssertEqual(count.label, "1 open")
XCTAssertEqual(newTitle.value as? String, "New task", "The field should be cleared")
row.tap()
XCTAssertEqual(row.value as? String, "done")
XCTAssertEqual(count.label, "0 open")
row.swipeLeft()
app.buttons["Delete"].tap()
XCTAssertFalse(row.exists)
}
}
It passed on the iOS 26.4 simulator in 7.8 seconds. Points worth copying:
-
Elements are declared once at the top and reused. Because elements are lazy descriptions (chapter 2),
rowstill works after the list re-renders. -
The test checks the starting state (
Adddisabled) before acting. If the precondition is wrong, the failure points at setup instead of at a confusing later step. - Every action is followed by an assertion on its effect: row exists, value, counter, cleared field. A test that only taps is a smoke test at best.
-
swipeLeft()thenapp.buttons["Delete"]: the swipe reveals the standard delete action, which is an ordinary button you can query.
The launch environment (UITEST_SKIP_LOGIN) starts the app on the task list so this test does not repeat the sign-in. Chapter 6 shows how the app reads it.
After typing into a SwiftUI text field and tapping Add, you assert XCTAssertEqual(newTitle.value as? String, "") to check the field was cleared. It fails with ("Optional("New task")") is not equal to ("Optional("")"). What is going on?
The failure message shows the placeholder text, which is what an empty field reports. If the text had stayed, the value would be "Water the plants". Reading the actual value in the failure message is faster than guessing at timing.
Assertions that explain themselves#
XCTest's assertion functions all take an optional message, and in UI tests it is worth writing one whenever the expression alone does not say what was expected:
XCTAssertTrue(app.staticTexts["login.error"].exists, "Expected an error for the wrong password")
XCTAssertEqual(count.label, "1 open") // XCTAssertEqual prints both values already
Prefer XCTAssertEqual(element.label, "...") over XCTAssertTrue(element.label == "..."): the first prints both values when it fails, the second only says "false".
Two more tools:
-
XCTUnwrapturns an optional into a value or a clear failure:let text = try XCTUnwrap(field.value as? String). -
XCTContext.runActivity(named:)groups steps under a name in the test report, which makes long tests readable in Xcode and in exported results.
A test taps a button that a newly added banner sometimes covers. Which behaviour should you expect from XCUITest?
XCUITest checks hittability before an element tap, so a fully covered element fails the tap. A partly covered one can still receive the event at its hit point, and then the next assertion catches the wrong screen. It does not wait for unrelated views to disappear; that is the test's job (chapter 4).
Next: the screens that do not change instantly, and how to wait for them without sleep().