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

iOS 9 Swift Programming Cookbook (2015)

Chapter 9. UI Testing

9.8 Tapping on UI Elements

Problem

You want to be able to simulate various ways of tapping on UI elements when writing your UI tests.

Solution

Use one or a combination of the following methods of the XCUIElement class:

§ tap()

§ doubleTap()

§ twoFingerTap()

NOTE

Double tapping is 2 taps, with 1 finger. The two finger tap is 1 tap, but with 2 fingers.

Discussion

Create a single view app and then add a gesture recognizer to the view that sets the accessibility of the view whenever two fingers have been tapped on the view:

class ViewController: UIViewController {

func handleTap(){

view.accessibilityValue = "tapped"

}

override func viewDidLoad() {

super.viewDidLoad()

view.isAccessibilityElement = true

view.accessibilityValue = "untapped"

view.accessibilityLabel = "myView"

let tgr = UITapGestureRecognizer(target: self, action: "handleTap")

tgr.numberOfTapsRequired = 1

tgr.numberOfTouchesRequired = 2

view.addGestureRecognizer(tgr)

}

}

Now our UI tests will do a two finger tap on the view and check its value before and after to make sure it checks out:

let app = XCUIApplication()

let view = app.descendantsMatchingType(.Unknown)["myView"]

XCTAssert(view.exists)

XCTAssert(view.value as! String == "untapped")

view.twoFingerTap()

XCTAssert(view.value as! String == "tapped")

See Also