Matti
Matti

Reputation: 484

UILabel's new text value not updating inside XCUI Test

So a few days ago I started using the 'new' XCUI Testing framework for tech evaluation purposes. I find the system quite shaky, as very often the tests start failing (typically, button presses using .tap() simply do not trigger the button action) and I need to restart Xcode and clear the DerivedData caches to get it working again. But this one thing I cannot get working at all - and it is about the simplest UI test use case available:

I have a UIButton and a UILabel. The UILabel initially has a text "initial text". The button's label is "SHOW MESSAGE". When the button is pressed, the label's text is changed to "new text". And obviously this works when running the app. ;)

However, when I run the following XCUI Test (app instance having been initialized and launch()ed in setup()):

    app.buttons["SHOW MESSAGE"].tap()
    XCTAssert(app.staticTexts["new text"].exists)

The test fails 100% of the time. When I print out (after the .tap() call) the static texts using print(app.staticTexts.debugDescription), I can see my label there but with the original text of "initial text".

Is all of this XCUI stuff still just REALLY alpha stuff or what?

Upvotes: 2

Views: 3056

Answers (3)

Matti
Matti

Reputation: 484

So it turns out this was about needing to add a 1 second sleep() in the setUp() method to allow for the framework to initialize properly. Sigh.

Upvotes: 1

emoleumassi
emoleumassi

Reputation: 5149

try it with expectationForPredicate. Here the code:

let exists = NSPredicate(format: "exists == 1")
let label = app.staticTexts["new text"]
expectationForPredicate(exists, evaluatedWithObject: label, handler: nil)
waitForExpectationsWithTimeout(5) { error in
            if error != nil {
                assertionFailure("error")
            }
        }

Cheers

Upvotes: 0

Oletha
Oletha

Reputation: 7649

Set an accessibility identifier on the label and retrieve the text using XCUIElement.label.

XCTAssertEqual("new text", app.staticTexts["yourAccessibilityLabel"].label)

This should retrieve the latest text from the label.

The a new view hierarchy snapshot should be taken after you tap the button. There should be a debug log showing this when you try to find the label's new value. It should not mention using any cached snapshot.

Upvotes: 0

Related Questions