How do I perform a tap and drag in Xcode UI Test scripts?
Asked Answered
I

2

8

For example, I have a sketch pad app that I want to test by drawing on it. I'd like to specify an (x,y) coordinate and make it tap and drag to another (x,y) coordinate.

Is this possible in Xcode UI Tests?

Joe provided a solution to this issue: Using objective C, my code looked something like this:

XCUICoordinate *start = [element2 coordinateWithNormalizedOffset:CGVectorMake(0, 0)];
XCUICoordinate *finish = [element2 coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)];
[start pressForDuration:0 thenDragToCoordinate:finish];

where element2 was the XCUIElement I had to perform the drag on.

Iona answered 8/12, 2015 at 19:44 Comment(0)
K
35

You can use XCUICoordinate to tap and drag elements in UI Testing. Here is an example of how to pull to refresh via table cell coordinates.

let firstCell = app.staticTexts["Adrienne"]
let start = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 0))
let finish = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 6))
start.pressForDuration(0, thenDragToCoordinate: finish)

If you don't have elements to reference you should be able to create arbitrary coordinates based off of XCUIApplication.

let app = XCUIApplication()
let fromCoordinate = app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 10))
let toCoordinate = app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 20))
fromCoordinate.pressForDuration(0, thenDragToCoordinate: toCoordinate)

UI Testing doesn't have official documentation, but I've scraped the headers and put together an XCTest Reference if you are interested in more details.

Kiln answered 8/12, 2015 at 20:29 Comment(1)
Thanks Joe! worked like a charm! only issue I had was trying to find the element to perform the actions on.Iona
M
6

Or as of Swift 4:

let view = window.staticTexts["FooBar"]
let start = view.coordinate(withNormalizedOffset: CGVector(dx: 10, dy: 20))
let finish = view.coordinate(withNormalizedOffset: CGVector(dx: 100, dy: 80))
start.press(forDuration: 0.01, thenDragTo: finish)
Mariejeanne answered 27/5, 2018 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.