Inti
Inti

Reputation: 3721

XCode UITesting check if a text field exists

I can't find any way to check if a text field exists without trying to get it which then fails the tests and shows an error if it can't be found. No matches found for TextField

Current code

XCUIElement *usernameTextField = app.textFields[@"username"];

Reason/detail

I've got a Objective C UITest in XCode which logs into my app in setUp and logs out in tearDown however sometimes my app is already logged in when the test starts (if the simulator has been used for anything else in the meantime). I'd like to be able to check to see if the username textfield exists in my setUp and then if it doesn't I can skip the login or call my logout function and continue as normal.

Upvotes: 1

Views: 1367

Answers (2)

Reinhard Männer
Reinhard Männer

Reputation: 15217

Here is the code in Swift, which can easily be converted to Obj-C:

// given:
// usernameTextField exists
// The username that is possibly entered there is "username".

// then:
if usernameTextField.value as! String == "username" {
  // logged in
} else {
  // not logged in
}

Upvotes: 0

user8094560
user8094560

Reputation: 11

Not sure about Obj-C but here's how it would work in Swift.

let usernameTextField = app.textFields["username"]
if usernameTextField.exists {
    do something
} else {
    do something else
}

Upvotes: 1

Related Questions