Typing Inside Text Fields - UI Testing - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 9. UI Testing

9.6 Typing Inside Text Fields

Problem

You want to write UI tests for an app that contains text fields. You want to be able to activate a text field, type some text in it, deactivate it, and then run some tests on the results, or a combination of the aforementioned scenarios.

Solution

Follow these steps:

1. Find your text field with the textFields property of your app or one of the other methods mentioned in Recipe 9.4.

2. Call the tap() method on your text field to activate it.

3. Call the typeText(_:) method on the text field to type whatever text that you want.

4. Call the typeText(_:) method of your app with the value of XCUIKeyboardKeyReturn as the parameter. This will simulate pressing the Enter button on the keyboard. Check out other XCUIKeyboardKey constant values such as XCUIKeyboardKeySpace orXCUIKeyboardKeyCommand.

5. Once you are done, read the value property of your text field element as String and do your tests on that.

Discussion

Create a single view app and place a text field on it. Set the accessory label of that text field to “myText”. Set your text field’s delegate as your view controller and make your view controller conform to UITextFieldDelegate. Then implement the notoriously redundant delegate method named textFieldShouldReturn(_:) so that pressing the return button on the keyboard will dismiss the keyboard from the screen:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

func textFieldShouldReturn(textField: UITextField) -> Bool {

textField.resignFirstResponder()

return true

}

}

Then inside your UI tests, let’s write the code similar to what I suggested in the solution section of this recipe:

let app = XCUIApplication()

let myText = app.textFields["myText"]

myText.tap()

let text1 = "Hello, World!"

myText.typeText(text1)

myText.typeText(XCUIKeyboardKeyDelete)

app.typeText(XCUIKeyboardKeyReturn)

XCTAssertEqual((myText.value as! String).characters.count,

text1.characters.count - 1)

See Also