Last active
January 14, 2022 16:08
-
-
Save yasirmturk/a1c899c071f3b25ec6bbd1475f985220 to your computer and use it in GitHub Desktop.
iOS/Swift Snapshot Test utility for UIView, UITableCell, UICollectionViewCell and SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
final class SnapshotContainer: UIView { | |
let view: UIView | |
init(_ view: UIView, width: CGFloat, backgroundColor: UIColor = .white) { | |
self.view = view | |
super.init(frame: .zero) | |
translatesAutoresizingMaskIntoConstraints = false | |
view.translatesAutoresizingMaskIntoConstraints = false | |
addSubview(view) | |
NSLayoutConstraint.activate([ | |
view.topAnchor.constraint(equalTo: topAnchor), | |
view.bottomAnchor.constraint(equalTo: bottomAnchor), | |
view.leadingAnchor.constraint(equalTo: leadingAnchor), | |
view.trailingAnchor.constraint(equalTo: trailingAnchor), | |
view.widthAnchor.constraint(equalToConstant: width) | |
]) | |
self.backgroundColor = backgroundColor | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import FBSnapshotTestCase | |
class SnapshotTestCase: FBSnapshotTestCase { | |
func XCTVerifyCollectionCell(wrapping cell: UICollectionViewCell) { | |
let container = SnapshotContainer(cell.contentView, width: 375) | |
FBSnapshotVerifyView(container, overallTolerance: 0.02) | |
} | |
func XCTVerifyCell(wrapping cell: UITableViewCell) { | |
let container = SnapshotContainer(cell.contentView, width: 375) | |
FBSnapshotVerifyView(container, overallTolerance: 0.02) | |
} | |
func XCTVerify(wrapping view: UIView) { | |
let container = SnapshotContainer(view, width: 375) | |
FBSnapshotVerifyView(container, overallTolerance: 0.02) | |
} | |
} | |
// MARK: - SwiftUI | |
import SwiftUI | |
extension SnapshotTestCase { | |
func XCTVerifySwiftUI<V: View>(wrapping sut: V) { | |
let viewController = UIHostingController(rootView: sut) | |
viewController.view.width(350) | |
viewController.view.drawHierarchy(in: viewController.view.bounds, afterScreenUpdates: true) | |
FBSnapshotVerifyView(viewController.view, overallTolerance: 0.02) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment