How to test that staticTexts contains a string using XCTest How to test that staticTexts contains a string using XCTest swift swift

How to test that staticTexts contains a string using XCTest


You can use NSPredicate to filter elements.

  let searchText = "the content of the staticText"  let predicate = NSPredicate(format: "label CONTAINS[c] %@", searchText)  let elementQuery = app.staticTexts.containing(predicate)  if elementQuery.count > 0 {    // the element exists  }

With CONTAINS[c] you specify that the search is case insensitive.

Have a look at Apples Predicate Programming Guide


First, you need to set an accessibility identifier for the static text object you want to access. This will allow you to find it without searching for the string it is displaying.

// Your app codelabel.accessibilityIdentifier = "myLabel"

Then you can assert whether the string displayed is the string you want by writing a test by calling .label on the XCUIElement to get the contents of the displayed string:

// Find the labellet myLabel = app.staticTexts["myLabel"]// Check the string displayed on the label is correctXCTAssertEqual("Expected string", myLabel.label)

To check it contains a certain string, use range(of:), which will return nil if the string you give is not found.

XCTAssertNotNil(myLabel.label.range(of:"expected part"))


I had this problem while I was building my XCTest, I had a dynamic string inside of my block of text I should verify. I had built this two functions to solve my problem:

func waitElement(element: Any, timeout: TimeInterval = 100.0) {    let exists = NSPredicate(format: "exists == 1")    expectation(for: exists, evaluatedWith: element, handler: nil)    waitForExpectations(timeout: timeout, handler: nil)}func waitMessage(message: String) {    let predicate = NSPredicate(format: "label CONTAINS[c] %@", message)    let result = app.staticTexts.containing(predicate)    let element = XCUIApplication().staticTexts[result.element.label]    waitElement(element: element)}

I know this post is old, but I hope this can help someone.