skip to content

An XCUITest tapping app.buttons["payButton"] fails now and then because the query matches two buttons; why does that happen, and how do you fix it?

level: seniorimportance: should knowfreq 55%

answer

  1. resolution happens at the tap
  2. zero or several matches raise an error
  3. element checks; firstMatch stops early
  4. a sheet leaving still holds a copy
  5. scope the query or make identifiers unique

basics

~20 s

tap() resolves the query when it runs, and several matches raise an error. A second view sharing the identifier, like a sheet still animating away, causes it. Wait for that view to go, scope the query, or make identifiers unique.

solid answer

~40 s

Queries are lazy: `tap()` resolves `app.buttons["payButton"]` at that moment, and if zero or several elements match, XCUITest raises an error. Intermittent double matches usually mean two views share an identifier for a moment, like a dismissing zone sheet and the checkout footer both showing a pay button. The subscript also matches labels and values, so a button labelled `payButton` counts too. Fix it by waiting for the old view with `waitForNonExistence(timeout:)`, scoping the query through its container (`app.otherElements["checkoutFooter"].buttons["payButton"]`), or giving the views different identifiers. Don't reach for `firstMatch` or `element(boundBy: 0)`: `firstMatch` stops at the first hit and never checks for duplicates, so it hides the ambiguity. To diagnose, assert `matching(identifier:).count` and print `debugDescription`.

code

swift · 19 lines
swift
import XCTest

final class CheckoutQueryUITests: XCTestCase {
    @MainActor
    func testPaysFromFooterOnly() {
        let app = XCUIApplication()
        app.launch()

        // The zone sheet also carries a pay button while it animates away.
        XCTAssertTrue(app.otherElements["zoneSheet"].waitForNonExistence(timeout: 5))

        let payButtons = app.buttons.matching(identifier: "payButton")
        XCTAssertEqual(payButtons.count, 1, app.debugDescription)

        // Scope the query to the container that owns the button.
        let pay = app.otherElements["checkoutFooter"].buttons["payButton"]
        pay.tap()
    }
}

go deeper

for a junior

Recall that a query is resolved when it is used, and that two matches make a tap raise an error.

for a middle

Explain element versus firstMatch versus element(boundBy:), and that the subscript also matches labels and values.

for a senior

Show the diagnosis: count the matches, read the tree, find the transition or shared identifier, then wait, scope or rename.

for a principal

Weigh a team rule for unique, context-bearing identifiers in reused components against fixing each flaky query as it appears.

## How a query becomes one element An `XCUIElementQuery` is a *description* of a search, not a result. Writing `app.buttons["payButton"]` searches nothing. The search runs when you use the element: an event like `tap()`, or a property like `exists`. Each use evaluates the query against the app's element tree *as it is at that moment*. The header for event methods is explicit: when an event API is called, the element is resolved, and **if zero or multiple matches are found, an error is raised**. So a test that is correct most of the time can fail whenever the tree briefly holds two matches. ## Where the second match comes from In a parking-payment app, the usual causes are: - **A transition.** The zone sheet has its own pay button and is still animating away while the checkout footer's pay button appears. For a moment both exist. - **Reused components.** One `PayButton` view used in two places, each setting the same `accessibilityIdentifier`. - **The subscript's breadth.** The subscript matches `identifier`, `title`, `label`, `value` or `placeholderValue`. A different button whose label or value happens to equal the string also matches. - **A larger layout.** On iPad, a split view can show the list and the detail together, each with its own copy of a control. Timing decides whether the race shows up, which is why a CI machine under load fails more often than a laptop. The same test can pass a hundred times on a fast simulator and fail on the first slow run, because the window where both buttons exist is only as long as the animation. ## The accessors and what each one promises | Accessor | Checks for duplicates | Behaviour | |---|---|---| | `query.element` | yes | traverses the tree and fails the test unless exactly one element matches | | `query.firstMatch` | no | stops at the first match; faster, but multiple matches go undetected | | `query.element(boundBy: n)` | no | binds to the result at index `n` | | `query["id"]` | at resolution | matches identifying properties; an event raises an error on zero or several | | `query.count` | n/a | evaluates now and returns how many match | Apple's documentation says to use `firstMatch` only when you know categorically that one element matches, and to use `element` when you want ambiguity to fail the test. So `firstMatch` is a speed tool for a large tree, not a fix for duplicates. `element(boundBy: 0)` silently picks whichever copy comes first, which during a transition may be the one about to vanish. ## Fixing it, in order of preference 1. **Wait for the view that is leaving.** `XCTAssertTrue(app.otherElements["zoneSheet"].waitForNonExistence(timeout: 5))` before the tap removes the transition race at its source. 2. **Scope the query.** `app.otherElements["checkoutFooter"].buttons["payButton"]` searches only inside the footer. `containing(_:identifier:)` helps when the container is known by its contents, for example the cell that contains the text "Zone 4021". 3. **Make identifiers unique.** Pass the context into a reused component (`payButton-footer`, `payButton-sheet`) so each copy says where it lives. 4. **Assert the count while diagnosing.** `XCTAssertEqual(app.buttons.matching(identifier: "payButton").count, 1, app.debugDescription)` fails with the element tree in the message. `matching(identifier:)` checks the same identifying properties as the subscript; to match the `identifier` attribute alone, filter with a predicate such as `identifier == "payButton"`. `debugDescription` on an element or query prints attributes, the descendant tree and each query step. Apple's documentation says to use it for debugging only, because its contents vary and a test must not depend on them. ## What not to do - Don't swap in `firstMatch` to make the error go away. The test now taps whichever button is found first, and the real bug, two live pay buttons, ships. - Don't add a `sleep` before the tap. It narrows the race on your machine and leaves it open on a slower one. - Don't match by label to dodge a shared identifier. Labels change with copy and language, which brings a second source of flakiness. ## Why it is a senior question The fix is simple once you know the facts, but finding it means knowing that queries are lazy, that resolution is strict about uniqueness, and that the accessor you pick decides whether ambiguity fails loudly or hides. An interviewer listens for "wait or scope, and keep `element` strict", not "use `firstMatch`".

  • When is firstMatch the right choice, then?
    When exactly one element can match and the tree is large, for example the only map view, `app.maps.firstMatch`. It stops traversing at the first hit, so it resolves faster than a check of the whole tree. If two matches are possible, use `element` or a scoped query so ambiguity fails the test.
  • Why does app.buttons["payButton"] match a button whose identifier is empty?
    The subscript compares the string with several identifying properties: identifier, title, label, value and placeholderValue. A button whose label reads "payButton", perhaps from a placeholder string nobody localized, matches too. Scope the query to its container, or match the identifier alone with a predicate, `app.buttons.matching(NSPredicate(format: "identifier == %@", "payButton"))`, and fix the label in the app.

  • Using firstMatch to make a multiple-matches error go away
  • Picking element(boundBy: 0) when two copies of a control exist
  • Believing a query is evaluated once when it is created
  • Adding a sleep before the tap to avoid the transition
  • Asserting on the text of debugDescription in a test