If you’re writing a UI test, the first things you’ll need to use are buttons and taps on them.
The first and easier example is a simple button with text.
You have a simple button:
Button(“Click me!”)
To get access to it you simply refer to it via text.
let app = XCUIApplication()
app.launch()
app.buttons[“Click me!”].tap()
Test code with XCUIApplication part is inside the UITest target.
Now, let’s take a look when the button isn’t a text but it’s an image.
Button(action: {
print(1)
}, label: {
Image(systemName: “star”)
})
And to get access to this button, just use the image name.
let app = XCUIApplication()
app.launch()
app.buttons[“star”].tap()
Let’s say you have a more complex button view and you need to use VStack.
Button(action: {
print(1)
}, label: {
VStack {
Image(systemName: “star”)
Image(systemName: “star.fill”)
Text(“Click me!”)
}
})
You could still get access to it using the text “Click me!” like this:
let app = XCUIApplication()
app.launch()
app.buttons[“Click me!”].tap()
It works fine but what in the case when there is a different language?
To solve this issue, you can use a unique identifier for this view to inform the UI test that this view is a button.
To do this use the accessibility identifier modifier for the whole button.
Button(action: {
print(1)
}, label: {
VStack {
Image(systemName: “star”)
Image(systemName: “star.fill”)
Text(“Click me!”)
}
})
.accessibilityIdentifier(“ViewWithTwoImagesAndText”)
And to get access to it use:
let app = XCUIApplication()
app.launch()
app.buttons[“ViewWithTwoImagesAndText”].tap()
Now, when you change the button view, you won’t need to change tests.
Sometimes, you might wonder why the view isn’t detected and you’re not sure what is going on. In these cases, you can simply print all buttons in the current view:
let app = XCUIApplication()
app.launch()
print(app.buttons)