Testing SwiftUI View Extensions

I have several extensions for SwiftUI Views that are a variation of the following-

extension View {
    func mockExtension() -> some View {
        # Relevant logic

How can I go about testing the above logic? Instantiating a view with said extension within a XCTestCase class has no effect, presumably because the the view is "detached". As a more concrete example, how can I test the below logic (borrowed from Observing Combine publishers in SwiftUI views | Swift by Sundell) which subscribes to the NotificationCenter publisher-

extension View {
    func onNotification(
        _ notificationName: Notification.Name,
        perform action: @escaping () -> Void
    ) -> some View {
            for: notificationName
        )) { _ in

From my understanding, testing the above would fall under the domain of Unit Testing (as opposed to UI testing) as the intent is to verify the execution of a particular block of code upon receiving a particular trigger.

Lastly, what effect would said extensions have on testing if they were defined within a Swift Package as opposed to an Xcode Project?

You use UI tests.

Given that the above extension is defined on View, you would need to create a UI test.

As long as you're not using a binary target, you can @testable import your package products into your app for UI testing. You cannot create UI tests in a swift package.

1 Like
Terms of Service

Privacy Policy

Cookie Policy