Cannot snapshot a UITableViewController but can snapshot UIViewController

161 views Asked by At

I am trying to snapshot a UITableViewController

I have a simple test class

class FeedSnapshotTests: XCTestCase {
    
    // Fails
    func test_empty_feed_one() {
        let sut = UITableViewController(style: .grouped)
        sut.loadViewIfNeeded()
        record(snapshot: sut.snapshot(), named: "EMPTY_FEED_ONE")
    }
    
    // Passes
    func test_empty_feed_two() {
        let sut = UIViewController()
        sut.loadViewIfNeeded()
        record(snapshot: sut.snapshot(), named: "EMPTY_FEED_TWO")
    }
}

private extension FeedSnapshotTests {
    func record(snapshot: UIImage, named name: String, file: StaticString = #filePath, line: UInt = #line) {
        guard let imageData = snapshot.pngData() else {
            return XCTFail("Failed to generate PNG data representation from snapshot", file: file, line: line)
        }
        
        let snapshotURL = URL(fileURLWithPath: String(describing: file))
            .deletingLastPathComponent()
            .appendingPathComponent("snapshots")
            .appendingPathComponent("\(name).png")
        
        do {
            try FileManager.default.createDirectory(at: snapshotURL.deletingLastPathComponent(), withIntermediateDirectories: true)
            try imageData.write(to: snapshotURL)
        } catch {
            XCTFail("Failed to record snapshot with error: \(error)", file: file, line: line)
        }
    }
}

extension UIViewController {
    func snapshot() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: view.bounds)
        return renderer.image(actions: { action in
            view.layer.render(in: action.cgContext )
        })
    }
}

At this point I am just attempting to create a UIImage and save to disk.

For some reason however, in the case of a UITableViewController I cannot snapshot the view. If I switch to a UIViewController this works.

When attempting to create a UImage of the UITableViewController my test always fails here

      guard let imageData = snapshot.pngData() else {
            return XCTFail("Failed to generate PNG data representation from snapshot", file: file, line: line)
        }
0

There are 0 answers