Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI testing firstMatch

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

like image 876
Alper Avatar asked Jan 03 '23 11:01

Alper


1 Answers

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
like image 73
Oletha Avatar answered Jan 11 '23 00:01

Oletha