Search code examples
iosswiftxctestui-testingxcuitest

iOS UI Test: Wait for exist fails for dynamically added button


My application does a SDK auto update and initialization when it launches. When it completed I am adding a button to check if auto update and initialization are completed in my UI test:

let hiddenButton = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
hiddenButton.setTitle("databaseUpdated", for: .normal)
hiddenButton.accessibilityIdentifier = "databaseUpdated"
self.view.addSubview(hiddenButton)

I have tried following lines to check it but it always fails:

XCTAssertTrue(app.descendants(matching: .button)["databaseUpdated"].waitForExistence(timeout: 60))
XCTAssertTrue(app.children(matching: .button)["databaseUpdated"].waitForExistence(timeout: 60))
XCTAssertTrue(app.otherElements["databaseUpdated"].waitForExistence(timeout: 60))
XCTAssertTrue(app.buttons["databaseUpdated"].waitForExistence(timeout: 60))

I have confirmed that my button is in view hierarchy using Debug View Hierarchy:

enter image description here

UPDATE

I have decided to add the button in viewDidLoad with different identifier and update it when SDK is initialized:

private let button = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))

override public func viewDidLoad() {
    super.viewDidLoad()
    button.isAccessibilityElement = true
    button.accessibilityTraits = .button
    button.accessibilityIdentifier = "initial"
    view.addSubview(button)
}

when SDK is initialized it is set to:

button.accessibilityIdentifier = "databaseUpdated"

and here is what I see when I inspect the button in view debugger:

accessibility attributes

still test is failing to find it.

UPDATE 2

I am able to find the button using Accessibility Inspector:

inspector


Solution

  • Check if the ViewController that you add the button is visible when you run the query. If not your query will fail.