示例工程 30-swiftui-mental-model
30-swiftui-mental-model/Tests/Ch30KitTests/ViewValueTests.swift
import SwiftUI
import Testing
@testable import Ch30Kit
@Suite("视图是值")
struct ViewValueTests {
@Test @MainActor func bodyIsReevaluatedOnEveryRender() {
let counter = BodyCounter()
_ = ImageRenderer(content: CountedLabel(text: "hi", counter: counter)).cgImage
#expect(counter.count == 1)
_ = ImageRenderer(content: CountedLabel(text: "hi", counter: counter)).cgImage
#expect(counter.count == 2)
}
@Test func counterModelMutates() {
let model = CounterModel()
model.increment()
model.increment()
#expect(model.value == 2)
model.reset()
#expect(model.value == 0)
}
@Test func observationFiresBeforeChange() {
let model = CounterModel(value: 1)
let fired = Flag()
withObservationTracking {
_ = model.value
} onChange: {
fired.value = true
}
model.value = 2
#expect(fired.value)
}
@Test func anyViewErasesConcreteType() {
let concrete = String(describing: type(of: Erasure.concrete("x")))
let boxed = String(describing: type(of: Erasure.boxed("x")))
#expect(concrete == "Text")
#expect(boxed == "AnyView")
}
@Test @MainActor func conditionalViewHasStableTypeForBothBranches() {
let on = String(describing: type(of: ConditionalDemo(flag: true).body))
let off = String(describing: type(of: ConditionalDemo(flag: false).body))
#expect(on == off)
#expect(on.contains("ConditionalContent"))
}
@Test @MainActor func viewBuilderCombinesChildren() {
let built = String(describing: type(of: pair("a", "b")))
#expect(built.contains("Tuple"))
}
private final class Flag: @unchecked Sendable {
var value = false
}
}