Does anyone know how to correctly write a UI test for a Toggle? Even in a brand new project with just a Toggle and nothing else in the entire UI I keep getting this sort of error:
Failed to get matching snapshot: Multiple matching elements found for <XCUIElementQuery: 0x60000108c410>.
Sparse tree of matches:
→Application, pid: 26580, label: 'TestToggle'
↳Window (Main)
↳Other
↳Other
↳Other
↳Other
↳Switch, label: 'Test switch', value: 1
↳Switch, label: 'Test switch', value: 1
UI looks like this:
struct ContentView: View {
@State private var toggleValue = true
var body: some View {
Toggle("Test switch", isOn: $toggleValue)
.padding()
}
}
Test looks like this (either of those lines gives me this same error):
func testExample() throws {
let app = XCUIApplication()
app.launch()
XCTAssertTrue(app.switches["Test switch"].value as? String == "1")
// XCTAssertTrue(app.switches["Test switch"].isEnabled)
}
Surely I’m doing something wrong. How can there be two switches showing up if there’s only one? None of the online articles seem to mention anything about this that I’ve seen. Any help appreciated. Thanks :)
I got a few responses in some slack channels and it turns out that for some reason using a Toggle I can't rely on the default label for testing (unlike Text and Button) and need to create a custom accessibility identifier.
So just add something like this:
Toggle("Test switch", isOn: $toggleValue)
.padding()
.accessibilityIdentifier("testSwitch")
and then test like this works:
func testExample() throws {
let app = XCUIApplication()
app.launch()
XCTAssertTrue(app.switches["testSwitch"].isEnabled)
XCTAssertTrue(app.switches["testSwitch"].value as? String == "1")
}