swiftdatepickerxcuitestuitest

iOS UI Test Dynamic Datepicker


I'm trying to refactor an existing UI test into something a little more robust. Basically I have code that looks like this:

let datePickers = XCUIApplication().datePickers
datePickers.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "June")
datePickers.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "1")
datePickers.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "2015")

However I would like to be able to pass in a MM/DD/YYYY date and have it dynamically use the spinner.

Aside from creating a large function that:

  1. Parses 01/01/2020 to 3 ints
  2. Translates the first int to a string (01) to (January)

Is there an easier way?


Solution

  • There's probably a better solution, but one way to do this is to simply use DateFormatters to convert your passed-in date to strings (provided that the strings in your date picker use the full-length month names and days without leading zeroes):

    extension DateFormatter {
        static let monthFormatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "MMMM"
            return formatter
        }()
    
        static let dayFormatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "d"
            return formatter
        }()
    
        static let yearFormatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy"
            return formatter
        }()
    }
    
    extension Date {
        var monthDayYearStrings: (month: String, day: String, year: String) {
            (DateFormatter.monthFormatter.string(from: self),
             DateFormatter.dayFormatter.string(from: self),
             DateFormatter.yearFormatter.string(from: self))
        }
    }
    

    And then use it in your test:

    let (month, day, year) = yourPassedInDate.monthDayYearStrings
    
    let datePickers = XCUIApplication().datePickers
    datePickers.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: month)
    datePickers.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: day)
    datePickers.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: year)