如何在SwiftUI快照测试中覆写无障碍环境属性值?
在SwiftUI快照测试中覆写无障碍环境属性
要验证SwiftUI视图对指定无障碍环境属性的响应,你可以直接借助SwiftUI的.environment修饰符,在快照测试环节为目标视图覆写这些属性值,再结合Point-Free快照测试库生成对应状态的快照。
单个属性覆写示例
以测试accessibilityDifferentiateWithoutColor开启状态为例,测试代码如下:
import XCTest import SnapshotTesting import SwiftUI final class MyViewTests: XCTestCase { func testAccessibilityDifferentiateWithoutColorEnabled() { let view = MyView() .environment(\.accessibilityDifferentiateWithoutColor, true) assertSnapshot(matching: view, as: .image) } }
多属性组合测试
若需验证多个属性同时生效的场景,可链式调用多个.environment修饰符:
func testCombinedAccessibilitySettings() { let view = MyView() .environment(\.accessibilityReduceTransparency, true) .environment(\.accessibilityReduceMotion, true) .environment(\.accessibilityInvertColors, true) assertSnapshot(matching: view, as: .image) }
批量覆盖所有属性状态
你可以遍历属性的布尔值组合,批量生成不同状态的快照,确保覆盖所有测试场景:
func testAllAccessibilityStates() { let accessibilityScenarios = [ (identifier: "differentiateWithoutColor_on", modifier: { $0.environment(\.accessibilityDifferentiateWithoutColor, true) }), (identifier: "differentiateWithoutColor_off", modifier: { $0.environment(\.accessibilityDifferentiateWithoutColor, false) }), (identifier: "reduceTransparency_on", modifier: { $0.environment(\.accessibilityReduceTransparency, true) }), (identifier: "reduceTransparency_off", modifier: { $0.environment(\.accessibilityReduceTransparency, false) }), (identifier: "reduceMotion_on", modifier: { $0.environment(\.accessibilityReduceMotion, true) }), (identifier: "reduceMotion_off", modifier: { $0.environment(\.accessibilityReduceMotion, false) }), (identifier: "invertColors_on", modifier: { $0.environment(\.accessibilityInvertColors, true) }), (identifier: "invertColors_off", modifier: { $0.environment(\.accessibilityInvertColors, false) }) ] for scenario in accessibilityScenarios { let modifiedView = scenario.modifier(MyView()) assertSnapshot(matching: modifiedView, as: .image, named: scenario.identifier) } }
注意:如果你的视图依赖其他环境值,需在测试时一并设置,保证测试环境的完整性。
内容的提问来源于stack exchange,提问作者Zev Eisenberg
相关产品推荐
相关产品推荐

