UI testing firstMatch
Asked Answered
O

1

5

Is it safe to replace all instances in my UI testing code of .element(boundBy: 0) with .firstMatch?

I would think so, but the documentation from Apple isn't very clear about it (especially in the case of multiple matches even though I only care about the first one). https://developer.apple.com/documentation/xctest/xcuielementtypequeryprovider/2902250-firstmatch

Obstruct answered 18/9, 2017 at 10:0 Comment(2)
Hmm good question. Off the top of my head I don't see why not.Agulhas
I swapped it out and it's looking good so far.Obstruct
P
9

Instead of swapping element(boundBy: 0) with firstMatch, you should chain them.

XCUIApplication().cells.element(boundBy:0).firstMatch

This will make the query resolve faster if there is more than one cell on-screen. Without firstMatch, the test will first get a list of all the cells and then use the first one. With firstMatch, the test will look for cells and use the first one it finds.

Only use firstMatch in cases where you know categorically that a single element will match a query.

You should still do element(boundBy:) anywhere where there could plausibly be more than 1 element matching the query, to ensure that when you use firstMatch, there is only one element that can match that query. In the situation where there are 3 cells and you want to use the first one, you should still use element(boundBy: 0). If you know you only have 1 cell on screen then it's fine to skip element(boundBy: 0) and use firstMatch instead of element to resolve the query faster.

// fine if there is only one cell
XCUIApplication().cells.element // also checks for multiple matches
// also fine if there is only one cell
XCUIApplication().cells.firstMatch // does not check for multiple matches
Perrie answered 18/9, 2017 at 22:40 Comment(4)
But what would be the problem of using firstMatch without element(boundBy: 0)? It seems to work right now.Obstruct
You are guarding against something that Apple calls 'surprising' results in their WWDC talk introducing this API. developer.apple.com/videos/play/wwdc2017/409 From what I understand, it will probably work without problems when the app is correct but when something goes wrong such that your element isn't found, firstMatch handles failure much less gracefully than other APIs.Perrie
I guess that makes sense. Already too many 'surprising' results in UI testing as it is.Obstruct
For what it's worth, I just ran into a situation where .element(boundBy: 0) exists, but .firstMatch doesn't, so I think there's more to the story...Heathen

© 2022 - 2024 — McMap. All rights reserved.