Search code examples
iosswiftxcodexcode-ui-testing

XCTest - How to query for substring in navbar title


I would like to be able to verify that a substring appears in the navigation bar in a UI test.

For example, if the nav bar title is "Rent Properties" then I can match it like so:

XCTAssert(XCUIApplication().staticTexts["Rent Properties"].exists)

However, this has two issues:

  • If the text is not in a nav bar it will still match
  • It does an exact match, whereas I want to be able to match a substring such as "Rent"

How can this be done?


Solution

  • For matching substring Rent, you can use the below code:

    XCUIApplication().staticTexts.matchingPredicate(NSPredicate(format: "label CONTAINS 'Rent'")).elementBoundByIndex(0)
    //it may contains one or more element with substring Rent.
    //you have to find out which element index you want in debug mode using p print() options.
    

    For the first option, there certainly must be a difference while element is showing or not showing. you have to find out it using po or p print option in debug mode.

    For example, there may the count is different or the element is not hittable or so on....

    you may try to use :

    let app = XCUIApplication()
    XCTAssert(app.staticTexts["Rent Properties"].exists)
    
    or 
    let app = XCUIApplication()
    app.staticTexts["Rent Properties"].hittable
    
    or
    let app = XCUIApplication()
    app.staticTexts["Rent Properties"].enabled
    
    or 
    
    app.staticTexts.matchingIdentifier("Rent Properties").count
    //take count while showing the text and take the count while not showing the text