iosswiftswiftuixctestpicker

iOS UI Test to adjust picker value on SwiftUI app


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


Solution

  • 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)