First off, I need to give a shout out to Jon Reid and Quality Coding. His blog at Quality Coding Blog it was through Jon's posts and live coding sessions where all of this code got fleshed out.
- For the Target, choose your Test Target
import SwiftUI
protocol ViewInspectorHook {
var viewInspectorHook: ((Self) -> Void)? { get set }
}
typealias TestableView = View & ViewInspectorHook
3. Create a new Swift File in your Test Target named UpdateTestableView.swift
and give it the following contents:
@testable import YOUR_PROJECT
import ViewInspector
import XCTest
extension XCTestCase {
@MainActor func inspectChangingView<V: TestableView>(
_ sut: inout V,
action: @escaping ((InspectableView<ViewType.View<V>>) throws -> Void),
file: StaticString = #filePath,
line: UInt = #line
) {
let expectation = sut.on(\.viewInspectorHook, file: file, line: line, perform: action)
ViewHosting.host(view: sut)
wait(for: [expectation], timeout: 0.01)
}
}
Note: All of this "boiler-plate" ViewInspector code is from Jon Reid and his QualityCoding coding sessions.
4. For any View that you want to test, add :TestableView
to the struct
and conform to the protocol by adding the following to the View
struct AppScreenView: TestableView {
.onAppear { self.viewInspectorHook?(self) }