---
title: Interactions and Assertions | TestingBot
description: 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…
source_url:
  html: https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions
  md: https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions.md
---

Course

[XCUITest Tutorial: iOS UI Testing in Swift](https://testingbot.com/resources/courses/xcuitest)

Chapter 4 of 11

1. [1 XCUITest Tutorial: iOS UI Test Automation in Swift](https://testingbot.com/resources/courses/xcuitest)
2. [2 Add a UI Test Target and Run Your First Test](https://testingbot.com/resources/courses/xcuitest/add-a-ui-test-target)
3. [3 Element Queries and Accessibility Identifiers](https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers)
4. [4 Interactions and Assertions](https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions)
5. [5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep)
6. [6 Screen Objects in Swift](https://testingbot.com/resources/courses/xcuitest/screen-objects)
7. [7 Launch Arguments and Environment: Control App State](https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment)
8. [8 Build for Testing: The App and the Test Runner](https://testingbot.com/resources/courses/xcuitest/build-for-testing)
9. [9 Run XCUITest on Real iPhones with TestingBot](https://testingbot.com/resources/courses/xcuitest/run-on-testingbot)
10. [10 XCUITest in CI with GitHub Actions](https://testingbot.com/resources/courses/xcuitest/ci-github-actions)
11. [11 XCUITest Knowledge Check](https://testingbot.com/resources/courses/xcuitest/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 4 of 11 Intermediate 6 min read 2 quick checks Updated Nov 2026 

# Interactions and Assertions
On this page
1. [Gestures](https://testingbot.com#gestures)
2. [Typing](https://testingbot.com#typing)
3. [Reading state back](https://testingbot.com#reading-state-back)
4. [A complete interaction test](https://testingbot.com#a-complete-interaction-test)
5. [Assertions that explain themselves](https://testingbot.com#assertions-that-explain-themselves)

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[#](https://testingbot.com#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:

```swift
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[#](https://testingbot.com#typing)

`typeText(_:)` types into the element that has keyboard focus. Tap the field first:

```swift
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 an `onSubmit` handler.
- To clear a field, tap it and type `XCUIKeyboardKey.delete.rawValue` repeated as many times as the value is long. There is no `clearText()` 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. `typeText` works either way, but do not assert on `app.keyboards` existing.

## Reading state back[#](https://testingbot.com#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 sets `accessibilityValue`.
- **`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[#](https://testingbot.com#a-complete-interaction-test)

`TaskFlowTests.swift` adds a task, ticks it off and deletes it, checking each step:

```swift
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), `row` still works after the list re-renders.
- **The test checks the starting state** (`Add` disabled) 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()` then `app.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 app did not clear the field; this is a real bug An empty text field reports its placeholder as its value, so the field was cleared and the assertion should expect the placeholder `value` is only updated after a `sleep`

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[#](https://testingbot.com#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:

```swift
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:

- **`XCTUnwrap`** turns 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?

 It taps the banner silently and the test continues It waits up to 60 seconds for the banner to go away The tap fails because the button is not hittable, or a later assertion fails because the tap went to the banner

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()`.

[Previous · Chapter 3 Element Queries and Accessibility Identifiers](https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers) [Next · Chapter 5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep)

On this page

1. [Gestures](https://testingbot.com#gestures)
2. [Typing](https://testingbot.com#typing)
3. [Reading state back](https://testingbot.com#reading-state-back)
4. [A complete interaction test](https://testingbot.com#a-complete-interaction-test)
5. [Assertions that explain themselves](https://testingbot.com#assertions-that-explain-themselves)

Certification

Earn the free, resume-worthy TestingBot XCUITest Certification for this course.

[How it works](https://testingbot.com/resources/courses/xcuitest/certification)
