8

I am testing an iOS Application and currently I am checking the existence of a particular XCUIElement using isHittable.

I wanted to know if we can also check the position of the XCUIElement on the view. For instance, if we have a button in the bottom right corner of the view, can we check if it is actually in the bottom right corner using XCTest framework?

I had a look at the Apple Documentation for XCTest framework but did not get any clue. Any help will be greatly appreciated.

Coder-256
  • 5,212
  • 2
  • 23
  • 51
Kushal Jogi
  • 265
  • 5
  • 15

2 Answers2

12

XCUIElement has a property frame which you can use to find the coordinates of the element in question.

let button = XCUIApplication().buttons["someButton"]
let frame = button.frame
let xPosition = frame.origin.x
let yPosition = frame.origin.y

There are other ways of retrieving different points relative to the frame, which is a CGRect, such as midX and midY, depending on how you want to assert the position of the element.

You should be aware that XCTest is a functional UI testing framework, and if you are using it for asserting the position of an element, the position will probably be different per device/simulator which may make your tests brittle.

Oletha
  • 7,324
  • 1
  • 26
  • 46
  • This will only work if all the objects in question are on the same background UIView frame, since object.frame will only give you the position relative to the parent object. Is there a way of getting the absolute position relative to the overall screen? – Charlie S Nov 15 '19 at 15:40
  • 1
    Hey Charlie :) it doesn't look like there's anything better than `frame` for this on an `XCUIElement`, but the docs for the property do say it's given in the screen coordinate space: https://developer.apple.com/documentation/xctest/xcuielementattributes/1500911-frame One must question why the absolute position matters in a functional UI test though ;) – Oletha Nov 19 '19 at 08:23
-2

Get the bounds of the element using:

let bounds = viewToTest.convert(viewToTest.bounds, to: nil)

Then check if the bounds are correct or not. Note that the bounds are relative to the top-left corner of the screen when held in portrait.

Coder-256
  • 5,212
  • 2
  • 23
  • 51