Recommended way to mock Kingfisher in tests? #1939
-
I'm trying to write some tests for a view in the app that contains an image that's loaded by Kingfisher. I have a couple options for the type of tests I could write, but I'm not finding a obvious way to mock out Kingfisher for use in tests. If I write a unit test, I can create a subclass of If I write a snapshot test, I can pass it a file url but that is asynchronously loaded after the snapshot is taken. Subclassing |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
I am not quite sure what kind of test you are trying to add, or say, can you paste some pseudo-code so we can have a more concrete context to discuss.
If a file URL is an option for your testing, then maybe this KF.url(fileURL)
.loadDiskFileSynchronously()
.set(to: imageView)
// Or if you prefer the image view extension:
imageView.kf.setImage(with: fileURL, options: [.loadDiskFileSynchronously]) |
Beta Was this translation helpful? Give feedback.
-
We're using https://github.com/pointfreeco/swift-snapshot-testing to take snapshots of our views in some of our tests. The goal was to have two tests, one to make sure the view had the correct appearance when the image hadn't loaded yet, and another for after the image did load. What I ended up doing is making a cache in the test and setting the default options on kingfisher to to only use that cache. Something like this. describe("appearance") {
beforeEach {
imageCache = ImageCache(name: self.name)
KingfisherManager.shared.defaultOptions = [
.onlyFromCache,
.targetCache(imageCache)
]
}
afterEach {
KingfisherManager.shared.defaultOptions = []
}
context("when the image hasn't loaded yet") {
beforeEach {
imageCache.clearMemoryCache()
view.configure(with: viewModel)
}
it("should have a dark background") {
expect(view).to(haveMatchingSnapshot())
}
}
context("when the image has loaded") {
beforeEach {
imageCache.store(
.placeholder,
forKey: expectedURL.cacheKey,
toDisk: false
)
view.configure(with: viewModel)
}
it("should show the image") {
expect(view).to(haveMatchingSnapshot())
}
}
} |
Beta Was this translation helpful? Give feedback.
-
Update
where Notify.Voucher.Place.mock.logo is URL Type |
Beta Was this translation helpful? Give feedback.
-
FYI this approach was broken by #2036 in 7.6.2 if you use |
Beta Was this translation helpful? Give feedback.
We're using https://github.com/pointfreeco/swift-snapshot-testing to take snapshots of our views in some of our tests. The goal was to have two tests, one to make sure the view had the correct appearance when the image hadn't loaded yet, and another for after the image did load.
What I ended up doing is making a cache in the test and setting the default options on kingfisher to to only use that cache. Something like this.