Reputation: 71
I am trying to implement a UI test that adjusts the selected value of the wheel of a sample picker like the following:
import SwiftUI
struct ContentView: View {
var colors = ["Red", "Green", "Blue", "Yellow", "White", "Black", "Purple", "Cyan"]
@State private var selectedColor = "Red"
var body: some View {
VStack {
Picker("Choose a color", selection: $selectedColor) {
ForEach(colors, id: \.self) {
Text($0)
}
}
.accessibility(identifier: "picker")
Text("You selected: \(selectedColor)")
}
}
}
UI test
let picker = app!.pickers["picker"].pickerWheels.firstMatch
picker.adjust(toPickerWheelValue: "Purple")
However, when using the function adjust(toPickerWheelValue: ) the wheel only steps to the next item on the list in the direction of the desired value. In the above UI Test example, the result is the wheel moving to "Green". If I call the function again, the wheel will move one step to select "Blue" and so on. Why is this happening?
Using: Xcode 12.4 and iOS 14.4
Upvotes: 6
Views: 1302
Reputation: 160
If your picker is inline styled(as it is by default), the picker and its content will look as Button on the accessibility hierarchy. I've done this steps on Xcode 16.1 to successfully select an option.
func testPickerSelection() throws {
let button = app.buttons["picker"]
let buttonExists = button.waitForExistence(timeout: 1)
if buttonExists {
button.tap()
let purpleOption = app.buttons["Purple"]
XCTAssertTrue(purpleOption.exists, "Purple option is not visible.")
purpleOption.tap()
XCTAssertEqual(button.label, "Choose a color, Purple", "Picker did not update correctly.")
} else {
XCTFail("Button can't be found.")
}
}
Upvotes: 0
Reputation: 14388
The behaviour of adjust(toPickerWheelValue:)
seems a bit counterintuitive. You could write your own function to accomplish the task:
extension XCUIElement{
func selectPicker(value: String, timeout: TimeInterval) {
let pickerWheel = pickerWheels.firstMatch
let row = pickerWheels[value]
while !row.waitForExistence(timeout: timeout) {
pickerWheel.adjust(toPickerWheelValue: value)
}
}
}
and then use it like this:
let picker = app.pickers["picker"]
picker.selectPicker(value: "Purple", timeout: 1)
Upvotes: 7