Search code examples
swiftxctestuitest

UITest compare value of element in expectation


I am currently trying to figure out when an activity indicator is on or off. I realised that, when on, its value is 1, 0 when off.

I am trying to check if that value is 1 or 0 like this:

let app = XCUIApplication()
let predicate = NSPredicate(format: "value == 0")
let expectation = expectation(
        for: predicate, 
        evaluatedWith: app.activityIndicators["activityId"],
        handler: nil)

if XCTWaiter().wait(for:[expectation], timeout: 20) == .completed {
    print ("Activity indicator is off")
} else {
    print ("Activity indicator is on")
}

The current problem is that the timeout is always reached. Whenever I set a breakpoint at the if and type this in the console:

po app.activityIndicators["activityId"].value

The result is:

Optional<Any>
- some : 0

However, after I let the test run again, the timeout is reached and the else branch is taken.

Can anyone see what I am doing wrong while accessing the value of the element in the expectation?

Thanks for your help in advance.


Solution

  • Assuming you've both launched your app and set the accessibility identifier of your activity indicator correctly (which it seems you've done), the reason your code doesn't work is that value is a string, not an integer.

    Replacing your predicate with the following will make your code work:

    let predicate = NSPredicate(format: "value == \"0\"")