How to test that staticTexts contains a string using XCTest

Vincent Phillips picture Vincent Phillips · Jun 27, 2016 · Viewed 18.3k times · Source

In Xcode UI testing, how do I test that staticTexts contains a string?

In the debugger, I can run something like this to print out all the content of staticTexts: po app.staticTexts . But how do I test if a string exists anywhere within all of that content?

I can check for the existence of each staticText doing something like app.staticTexts["the content of the staticText"].exists? but I have to use the exact content of that staticText. How can I use only a string which may be only a part of that content?

Answer

dnlkng picture dnlkng · Nov 12, 2017

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