Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active July 24, 2024 15:23
Show Gist options
  • Save perlguy99/10f160439ca112866155b36f43d73d02 to your computer and use it in GitHub Desktop.
Save perlguy99/10f160439ca112866155b36f43d73d02 to your computer and use it in GitHub Desktop.
Adding ViewInspector to your project

HowTo add ViewInspector to a Project

Shout Out!

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.

1. Add ViewInspector branch 0.10.0 to your project

  • For the Target, choose your Test Target

2. Create a file named TestableView.swift with the following contents:

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

Add:

struct AppScreenView: TestableView {

Also, add the following to the body of the View:

.onAppear { self.viewInspectorHook?(self) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment