lundi 29 mars 2021

Unit testing by manipulating state variable - SwiftUI

I have a ContentView that generates a random paragraph.

import SwiftUI
import LoremIpsum

struct ContentView: View {
    @State private var text = ""
    @State private var wordCount: Int = 0
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            TextEditor(text: $text)
                .font(.body)
                .lineSpacing(16)
                .disableAutocorrection(true)
                .padding()
                .onChange(of: text) { value in
                    let words = text.split {
                        $0 == " " || $0.isNewline
                    }
                    self.wordCount = words.count
                }
            
            Text("\(wordCount) words")
                .font(.headline)
                .foregroundColor(.secondary)
                .padding(.trailing)
        }
        
        Button("Generate random text") {
            text = String.loremIpsum(paragraphs: 1)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

How would I create a unit test that tested for the correct wordCount and also if the text state corresponded to the loremIpsum paragraph?

I've tried playing about with the ViewInspector package that lots of people are discussing, although I'm not sure how you can actually manipulate the state with it.

Is this something that can be done with either unit or UI tests?

Aucun commentaire:

Enregistrer un commentaire