<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikolay Suvandzhiev on Medium]]></title>
        <description><![CDATA[Stories by Nikolay Suvandzhiev on Medium]]></description>
        <link>https://medium.com/@sovata8?source=rss-b983d7767475------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pe-DoODIZ05XxVG6v9NpPQ.jpeg</url>
            <title>Stories by Nikolay Suvandzhiev on Medium</title>
            <link>https://medium.com/@sovata8?source=rss-b983d7767475------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:40:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sovata8/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Xcode UI testing — button interactions — exploring `tap()`, `exists` and waiting with predicates]]></title>
            <link>https://medium.com/@sovata8/xcode-ui-testing-button-interactions-exploring-tap-exists-and-waiting-with-predicates-1e344b3c2e60?source=rss-b983d7767475------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e344b3c2e60</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Nikolay Suvandzhiev]]></dc:creator>
            <pubDate>Mon, 30 May 2022 23:05:59 GMT</pubDate>
            <atom:updated>2022-05-30T23:05:59.177Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Xcode UI testing — button interactions — exploring `tap()`, `exists` and waiting with predicates</strong></h3><blockquote>tl;dr: When doing iOS UI testing, tapping on a button with tap() is not very strict — it does not fail even if a button is disabled or with zero frame. Also, it’s possible to wait on a button to become hittable or enabled (with predicates), and then assert on the result of the wait.</blockquote><blockquote>The observations in this article are made on iOS 15 and Xcode 13</blockquote><p>As iOS developers, we’ve seen the UI test tools mature through the years. They form an essential part of our development process — both for actual UI testing, but also for things such as automated screenshots.</p><p>At <a href="https://www.medtronic.com/">Medtronic</a> — as part of working on the <a href="https://medium.com/u/9174253ffa7">Touch Surgery</a> app, we have build a comprehensive suite of Unit, Integration and UI tests. When working on UI tests recently, we discovered some interesting aspects and subtle (even unexpected) behaviours when it comes to tapping on a button, or waiting for a button to become hittable, enabled or to exist.</p><p>Here we share our findings.</p><h3>The setup</h3><p>To test all kinds of button setup cases, we created a sample app (<a href="https://github.com/sovata8/UITestsButtonTapAndWaiting">GitHub link</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGBMBWBQMG6p7iVImkoerg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVM5BHOdfawJxrk18WNUwg.png" /></figure><p>As you can see we have all kinds of situations — buttons being disabled, hidden, with zero frame, off screen, covered by other views etc.</p><p>We then created some UI tests and observed the behaviour.</p><h3>What `tap()` does in different button situations</h3><p>A very common thing to do in UI tests is:</p><pre>let goButton = app.buttons[&quot;go_button&quot;].firstMatch<br>goButton.tap()</pre><p>Looking at our sample app, we discovered the following:</p><ul><li>tap() proceeds without a warning or an error even when isEnabled or isUserInteractionEnabled are false.</li><li>tap() fails (as expected) when the element is covered by another view or clipped (embedded in a view, but outside of its bounds).</li><li>tap() fails (as expected) whenisHidden is true.</li><li>tap() can’t tap a button that is off-screen, or on the screen by less than 5 pt, even if it’s potentially possible to tap (at least in the Simulator with the cursor)</li><li>tap() actually can tap a button with frame width and height of zero, which won’t be possible for a user.</li></ul><p>Some of these behaviours might be surprising for developers. For example the fact that a UI test will happily proceed to “<em>tap()</em>” a button that is not even enabled — there is no warning or error, the test code just continues running. This tap() does not actually cause the button to be considered “tapped” by your production code in the app (thankfully!). Imagine the common situation in which the button tap is supposed to show some other screen or UI and your test later makes some assertions about this screen. Of course the test will fail because the screen was not shown at the first place, the “tap” didn’t actually happen.</p><p>You as a developer might end up spending time investigating the issue with your screen, when it would have been easier if the test failed earlier, at the tap() step. This can be achieved by creating a custom, more “assertive” tap() which checks for isEnabled — we’ll explore this later in the article.</p><p>Another interesting observation is that a button with an empty frame (width and height of 0) is not really tappable in practice by your users, but the UI test will silently proceed.</p><h3>Waiting for existence or other expectations with predicates</h3><p>XCUIElement already has a useful function:</p><pre>/** Waits the specified amount of time for the element&#39;s exist property to be true and returns false if the timeout expires without the element coming into existence. *<em>/</em></pre><pre>open func waitForExistence(timeout: TimeInterval) -&gt; Bool</pre><p>In some cases, for example when animated transitions are involved, or when some processing or loading causes a small delay, this function can ensure that the test waits until it attempts to tap a button for example.</p><p>But what if we want to wait for other conditions, for example a button becoming enabled or hittable? In such cases we can use XCTNSPredicateExpectation to create XCTestExpectation from NSPredicate. Then using theXCTestCase wait() or XCTWaiter, we can wait for these expectaions. Putting it altogether looks something like this:</p><pre>extension XCUIApplication {<br>    func waitFor(element: XCUIElement,<br>                 predicate: NSPredicate,<br>                 timeout: TimeInterval = 1) -&gt; XCTWaiter.Result {<br>        let expectation = XCTNSPredicateExpectation(predicate: predicate,<br>                                                    object: element)<br>        return XCTWaiter().wait(for: [expectation],<br>                                timeout: timeout)<br>    }<br>}</pre><p>Here we’ve done it as an extension on XCUIApplication, but of course it can be done as an extension on XCTestCase or on XCUIEelement.</p><p>The NSPredicate construction uses a stringly typed API, for exampleNSPredicate(format: &quot;hittable == true&quot;). We can make this less stringly typed (but admittedly longer and harder to read) by using Swift’s keyPath feature, and putting in an extension looks like this:</p><pre>extension NSPredicate {<br>    static let exists = NSPredicate(format: &quot;\(#keyPath(XCUIElement.exists)) == \(true)&quot;)<br>    static let hittable = NSPredicate(format: &quot;\(#keyPath(XCUIElement.isHittable)) == \(true)&quot;)<br>    static let enabled = NSPredicate(format: &quot;\(#keyPath(XCUIElement.isEnabled)) == \(true)&quot;)<br>}</pre><p>Putting all of this together we get for example:</p><pre>let goButton = app.buttons[&quot;go_button&quot;].firstMatch<br>app.waitFor(goButton, .enabled)<br>goButton.tap()</pre><h4>Important — the test will proceed even if the `wait()` times out</h4><p>There’s an important detail here — in the last example, if we run the test — the wait() won’t actually fail / throw an error even if the button does not become enabled. The test will wait (up to the timeout defined) and then just proceed with the test logic. This is because we told the test to wait, but we never told it to “assert” that the expectation was met. To do this, we need to actually add an assertion.</p><pre>let goButton = app.buttons[&quot;go_button&quot;].firstMatch<br>XCTAssertEqual(app.waitFor(goButton, .enabled), .completed)<br>goButton.tap()</pre><p>As we see, we assert that the wait result is .completed (as opposed to .timedOut for example). This then ensures the expectation (predicate) is fulfilled. The same applies for the native waitForExistance — we would need to do XCTAssertTrue(buttonGo.waitForExistence(timeout: 1)).</p><h3>Checking if a en element is visible and on screen</h3><p>XCUIElement has the property exists but as the sample app reveals — this does not actually guarantee that the element is on screen. To achieve this, a quick look at StackOverflow suggest a useful extension:</p><pre>extension XCUIElement {<br>    var isVisible: Bool {<br>        guard exists &amp;&amp; !frame.isEmpty else { return false }<br>        let frameOfWindow = XCUIApplication().windows.element(boundBy: 0).frame<br>        return frameOfWindow.contains(frame)<br>    }<br>}</pre><p>A couple of notes:</p><ul><li>The “contains” implies “fully contained within the frame” — so even if just a small part of the element is off-screen, isVisible will report false.</li><li>No need to check for isHidden becauseexists implies it.</li><li>No need to check for alpha != 0 because exists implies it.</li><li>This does not check if the element is actually covered by other elements or clipped out of the bounds of its superview. If working with buttons, isHittable can do these checks.</li><li>This code probably won’t work as expected for apps with multiple windows.</li></ul><h3>A quirk with the new Xcode button system `frame`</h3><p>With iOS 15 Apple inroduced a new button system — e.g. button styles such as “tinted” and “filled”.</p><p>In our isVisible extension, we make a check for an empty frame. This makes sense, because by default a frame with zero width and height is actually considered “contained” inside another frame — but for most practical purposes we do not consider such an element to bevisible .</p><p>If you check in UI tests for the frame of a XCUIElement button, this can cause some confusion. Due to some internal UIKit implementation of the new button system, a button might have an emptyframe of (0, 0), but still report a small frame of (24,14). The UI debugger reveals that the UIButton has an invisible subview with this frame, and that’s what the XCUIElement .frame reports. If you set the button’s “Type” to “Custom” (as opposed to “System”) and the “Style” to “Default” (as opposed to “Plain”), this issue does not occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L7_F9gPKs2YklWCEQgNSA.png" /></figure><h3>Making a custom, more “assertive” tap</h3><p>If we take all we’ve learned and put it together, we can create a much more assertive tap() — one that checks for existence, visibility and isEnabled:</p><pre>extension XCUIElement {<br>    func strictTap(app: XCUIApplication = XCUIApplication(),<br>                   file: StaticString = #file,<br>                   line: UInt = #line) {<br>        XCTAssertTrue(self.isVisible, file: file, line: line)<br>        XCTAssertTrue(self.isEnabled, file: file, line: line)<br>        self.tap()<br>    }<br>}</pre><p>And we can even have a strict put patient tap() using the waiting method:</p><pre>extension XCUIElement {<br>    func strictTapWithWait(timeout: TimeInterval = 1,<br>                           app: XCUIApplication = XCUIApplication(),<br>                           file: StaticString = #file,<br>                           line: UInt = #line) {<br>        let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [.exists,<br>                                                                            .enabled])<br>        XCTAssertEqual(app.waitFor(element: self, predicate: predicate, timeout: timeout), .completed, file: file, line: line)<br>        XCTAssertTrue(self.isVisible, file: file, line: line)</pre><pre>self.tap()<br>    }<br>}</pre><p>Note that we don’t need to check for isHittable because the native tap() works if and only if isHittable is true. We also don’t have to worry about isUserInteractionEnabled, because XCUIElement.isEnabled implies it.</p><h3>That’s all, happy button tapping!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bCK20oJ59BeQff7IU0saRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e344b3c2e60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>