ios – SwiftUI structure for view unit testing

Spread the love

We’ve an app constructed with SwiftUI, utilizing MVVM structure, and we wish to implement unit testing on the view stage. So, to offer an instance, that is how a view would seem like:

struct RandomView<InjectedModel>: View the place InjectedModel: InjectedModelViewModelProtocol {
    @StateObject var viewModel: InjectedModel

        viewModel: @autoclosure @escaping () -> InjectedModel
    ) {
        self._viewModel = StateObject(wrappedValue: viewModel())

And a view mannequin protocol could be represented by an interface corresponding to:

protocol InjectedModelViewModelProtocol: ObservableObject {
    var someProperty: String { get set }
    func someMethod()

The explanation for doing that is that we wish to mock the view mannequin and check the view to see the right values / components within the fields and so forth (for reference, we’ll nonetheless use the XCUIElement and the remainder of the APIs obtainable in customary UI testing).

This works up to now and it permits for the view mannequin to be mocked when working the exams. However now, the questions: is it okay for the views to have the view fashions injected on this method, in regards to the efficiency and different SwiftUI behaviours? We’re planning to have each small view constructed like this. And I do know Apple mentions in one in all its WWDC speak to not have actually something to adapt to protocols. Additionally, undecided how good this way of working with view mannequin’s properties is, and if we cannot hit any limitations or different issues.

I’ve tried this answer and works for small iteration, however was questioning from a perspective of long run improvement.

Leave a Reply

Your email address will not be published. Required fields are marked *