Swift - How do you test whether a label has been updated when a button is tapped
Asked Answered
B

2

6

I've go a very simple calculator and I' trying to test whether a label gets updated when a button is tapped.

My test method looks like this:

let app = XCUIApplication()
app.buttons["9"].tap()

I can visually see the Label being updated but I'm not sure how to test it.

I think I need to use XCUIElementQuery API to query label and then assert that the label text has changed. I'm just not sure how to do that.

I'm not sure about the following questions:

  • Do I need to know what the value is for the label to be able to query?
  • Is there a way of querying for the label without knowing what the value is when the application starts?
Bravado answered 23/5, 2016 at 18:25 Comment(0)
T
9

With UI Testing you might have to think about your problem a little differently. Instead of asserting that something changed, check if the new thing exists.

In practice, this means to check that a label with your expected value appears. Don't check that an existing one changed to the correct state.

So, in your example, you can do the following. This will check that when you tap the "9" button a label with the text "42" appears.

let app = XCUIApplication()
app.buttons["9"].tap()
XCTAssert(app.staticTexts["42"].exists)
Thill answered 23/5, 2016 at 18:39 Comment(2)
Does staticTexts refer to the label text or could it refer to the button's text value?Bravado
staticTexts only refers to labels, use buttons for a UIButton.Thill
U
5

I would say you set the distinct accessibilityLabel or accessibilityIdentifierfor the button you want to tap, and then compare the values before and after tap() and check if label has changed using XCTAssertNotEqual assertion,

In the application code :

button.accessibilityIdentifier = "TappableButton"

Then in test file :

let app = XCUIApplication() let buttonLabel = app.buttons["TappableButton"].label app.buttons["TappableButton"].tap() XCTAssertNotEqual(buttonLabel, app.buttons[TappableButton].label)

Ulbricht answered 23/5, 2016 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.