Swiping on UI Elements - UI Testing - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 9. UI Testing

9.7 Swiping on UI Elements

Problem

You want to simulate swiping on various UI components in your app.

Solution

Use the various swipe methods on XCUIElement such as the following:

§ swipeUp()

§ swipeDown()

§ swipeRight()

§ swipeleft()

Discussion

Let’s set our root view controller to a table view controller and program the table view controller so that it shows 10 hardcoded cells inside it:

class ViewController: UITableViewController {

let id = "c"

lazy var items: [String] = {

return Array(0..<10).map{"Item \($0)"}

}()

override func tableView(tableView: UITableView,

numberOfRowsInSection section: Int) -> Int {

return items.count

}

override func tableView(tableView: UITableView,

cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let c = tableView.dequeueReusableCellWithIdentifier(id,

forIndexPath: indexPath)

c.textLabel!.text = items[indexPath.row]

return c

}

override func tableView(tableView: UITableView,

commitEditingStyle editingStyle: UITableViewCellEditingStyle,

forRowAtIndexPath indexPath: NSIndexPath) {

items.removeAtIndex(indexPath.row)

tableView.deleteRowsAtIndexPaths([indexPath],

withRowAnimation: .Automatic)

}

}

With this code, the user can swipe left on any cell and then press the Delete button to delete that cell. Let’s test this in our UI test. This is what I am going to do:

1. Get the handle to the app.

2. Using the cells property of the app, I am going to first count to make sure there are initially 10 items in the table view.

3. I am then going to find the 5th item and swipe left on it.

4. I will then find the “Delete” button using the buttons property of the app object and tap on it with the tap() method.

5. Then I will assert that the cell was deleted for sure by making sure the cell’s count is now 9 instead of 10.

let app = XCUIApplication()

let cells = app.cells

XCTAssertEqual(cells.count, 10)

app.cells.elementBoundByIndex(4).swipeLeft()

app.buttons["Delete"].tap()

XCTAssertEqual(cells.count, 9)

See Also