Skip to content

Commit

Permalink
Merge branch 'GetSelectedValueFromPicker' of https://github.com/tobyw…
Browse files Browse the repository at this point in the history
…oollaston/ViewInspector into tobywoollaston-GetSelectedValueFromPicker
  • Loading branch information
Alexey Naumov committed May 2, 2023
2 parents 4aa8923 + 827861b commit c58271d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Sources/ViewInspector/SwiftUI/Picker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ public extension InspectableView where View == ViewType.Picker {
}
casted.forEach { $0.wrappedValue = value }
}

func selectedValue<SelectionValue>() throws -> SelectionValue {
var bindings = try Inspector.attribute(path: "selection", value: content.view)
if let single = bindings as? Binding<SelectionValue> {
bindings = [single]
}
let typeName = Inspector.typeName(value: bindings)
guard let casted = bindings as? [Binding<SelectionValue>] else {
var endIndex = typeName.index(before: typeName.endIndex)
if typeName.hasPrefix("Array") {
endIndex = typeName.index(before: endIndex)
}
let expected = typeName[..<endIndex]
.replacingOccurrences(of: "Array<Binding<", with: "")
.replacingOccurrences(of: "Binding<", with: "")
let factual = Inspector.typeName(type: SelectionValue.self)
throw InspectionError
.notSupported("selectedValue() expected a value of type \(expected) but received \(factual)")
}
return casted.first!.wrappedValue
}
}

// MARK: - Global View Modifiers
Expand Down
13 changes: 13 additions & 0 deletions Tests/ViewInspectorTests/SwiftUI/PickerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ final class PickerTests: XCTestCase {
XCTAssertEqual(try view.inspect().find(text: "xyz").pathToRoot,
"anyView().picker().text(1)")
}

func testGetSelectedValue() throws {
let binding = Binding<String>(wrappedValue: "First Option")
let view = Picker(selection: binding, label: Text("Title")) {
Text("First Option").tag(0)
Text("Second Option").tag(1)
}
try view.inspect().picker().select(value: "Second Option")

XCTAssertThrows(try view.inspect().picker().selectedValue() as Int,
"selectedValue() expected a value of type String but received Int")
XCTAssertEqual("Second Option", try view.inspect().picker().selectedValue())
}
}

// MARK: - View Modifiers
Expand Down

0 comments on commit c58271d

Please sign in to comment.