Skip to content

Instantly share code, notes, and snippets.

@dreampiggy
Last active February 2, 2020 04:25
Show Gist options
  • Save dreampiggy/0b83d31428b3bed0e5be7ffd7ac4aa02 to your computer and use it in GitHub Desktop.
Save dreampiggy/0b83d31428b3bed0e5be7ffd7ac4aa02 to your computer and use it in GitHub Desktop.
AnimatedImage Unit Testing with UIViewRepresentable and ViewInspector
extension AnimatedImage {
struct WrapperView: View & Inspectable {
var name: String
var bundle: Bundle?
@State var isAnimating: Bool
var onViewUpdate: (Self, PlatformView, AnimatedImage.Context) -> Void
var body: some View {
AnimatedImage(name: name, bundle: bundle, isAnimating: $isAnimating)
.onViewUpdate { view, context in
self.onViewUpdate(self, view, context)
}
}
}
}
func testAnimatedImageBinding() throws {
let expectation = self.expectation(description: "AnimatedImage binding control")
var viewUpdateCount = 0
// Use wrapper to make the @Binding works
let wrapperView = AnimatedImage.WrapperView(name: "TestLoopCount.gif", bundle: TestUtils.testImageBundle(), isAnimating: true) { wrapperView, view, context in
viewUpdateCount += 1
guard let animatedImageView = view as? SDAnimatedImageView else {
XCTFail("AnimatedImage's view should be SDAnimatedImageView")
return
}
if let animatedImage = animatedImageView.image as? SDAnimatedImage {
XCTAssertEqual(animatedImage.animatedImageLoopCount, 1)
XCTAssertEqual(animatedImage.animatedImageFrameCount, 2)
} else {
XCTFail("AnimatedImage's image should be SDAnimatedImage")
}
switch viewUpdateCount {
case 1:
// #1 SwiftUI's first-time updateUIView call
#if os(iOS) || os(tvOS)
XCTAssertTrue(animatedImageView.isAnimating)
#else
XCTAssertTrue(animatedImageView.animates)
#endif
case 2:
// #2 AnimatedImage's imageModel @ObservedObject trigger update
#if os(iOS) || os(tvOS)
XCTAssertTrue(animatedImageView.isAnimating)
#else
XCTAssertTrue(animatedImageView.animates)
#endif
DispatchQueue.main.async {
wrapperView.isAnimating = false
}
case 3:
// #3 AnimatedImage's isAnimating @Binding trigger update (from #2)
#if os(iOS) || os(tvOS)
XCTAssertFalse(animatedImageView.isAnimating)
#else
XCTAssertFalse(animatedImageView.animates)
#endif
expectation.fulfill()
default:
// Should only update 3 times
XCTFail()
}
}
ViewHosting.host(view: wrapperView)
self.waitForExpectations(timeout: 5, handler: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment