Reputation: 3941
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 :)
Upvotes: 7
Views: 2939
Reputation: 3941
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")
}
Upvotes: 10
Reputation: 640
I am not sure why you are getting the error you are getting, but you could try adding a accessibilityIdentifier
to the Toggle and find it that way.
For example:
struct ContentView: View {
@State private var toggleValue = true
var body: some View {
Toggle("Test switch", isOn: $toggleValue)
.padding()
.accessibilityIdentifier("testSwitch")
}
}
And in your test, you can then find the element with:
func testExample() throws {
let app = XCUIApplication()
app.launch()
XCTAssertTrue(app.switches["testSwitch"].value as? String == "1")
}
By the way, if you want to test whether the Toggle is on or off, you should not use isEnabled
. This will check "whether or not the element is enabled for user interaction."
You should use
app.switches["testSwitch"].value as? String == "1" // on
or
app.switches["testSwitch"].value as? String == "0" // off
depending on what you want to test.
Upvotes: 1