0

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)
        }
Teddy K
  • 820
  • 1
  • 6
  • 17
  • What do you mean by "I cannot snapshot the view"? What error/unexpected thing do you get? – Sweeper Oct 09 '20 at 04:52
  • Sorry, when running the tests, the first test fails on "Failed to generate PNG data representation from snapshot" - I am expecting it to create a `UIImage` of the tableview. The second test passes, however this is a plan UIViewController. – Teddy K Oct 09 '20 at 04:55
  • The short answer is, `UITableViewController.view` starts off with `bounds` being (0, 0, 0, 0). But I'm guessing that is not satisfying enough and you are going to ask me why does it start off with `bounds` being (0, 0, 0, 0). Well, I don't know. :-) – Sweeper Oct 09 '20 at 05:04

0 Answers0