How To Create Custom Button For UI Tests

You know how to use the button for UI Tests from this post. Now it’s time to create a custom one.

Let’s say for some reason you want to create custom tap handling and you don’t want to use Button view.

Simple code:

VStack {
    
Text(“Button Text”)
    
Image(systemName: “star”)
}
.
onTapGesture {
    
print(“Click”)
}

On each tap on Text or Image, there is print “Click”.

However, you can’t get access to this button from UI Tests.

This code:

let app = XCUIApplication()
app.
launch()
app.
buttons[“Button Text”]

Or this:

let app = XCUIApplication()
app.
launch()
app.
buttons[“star”]

Both of them will crash your test.

Why? Because UI Test doesn’t see this view as a button.

You need to inform that VStack is a button, you can do it by adding .accessibility(addTraits: .isButton) modifier.

VStack {
    
Text(“Button Text”)
    
Image(systemName: “star”)
}
.
accessibility(addTraits: .isButton)
.
onTapGesture {
    
print(“Click”)
}

Now, you can get access to Text via its text or to Image via its image name.

To improve it you can add .accessibilityIdentifier(“CustomButton”) modifier to make it resistant for testing, more about it you can read here.