dragxcode-ui-testingxcuielement

Xcode UI Test: How to move an XCUIElement to another position on the screen?


My app displays map annotations that can be dragged to another position of the map. I want to write a UI test that checks what happens when dragging stops.

I found a way (see the docs) to drag an XCUIElement to another XCUIElement using

pressForDuration:thenDragToElement:withVelocity:thenHoldForDuration:

I also found a way (see here) to drag the map by pressing and dragging a coordinate.

But I did not find a way to move the element from its current coordinate to another coordinate. This requires to long press the element, and drag it then to the target coordinate.

How can this be done?


Solution

  • Problem solved:
    I used the code in this answer, applied to my XCUIElement pin:

    let start  = pin.coordinate(withNormalizedOffset: CGVector(dx: 0.0, dy: 0.0))
    let finish = pin.coordinate(withNormalizedOffset: CGVector(dx: 3.0, dy: 3.0))
    start.pressForDuration(1.0, thenDragToCoordinate: finish)  
    

    but I was not aware that the normalized offset is relative the the elements origin.
    A normalized offset of CGVector(dx: 0.0, dy: 0.0) is thus the exact origin of the element, and a press at this point is apparently considered as a press to the background, not to the element itself. Thus, my map was dragged.

    When I use

    let start  = pin.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
    

    the element is pressed at its center, and the element is dragged.