pointfreeco / swift-snapshot-testing

📸 Delightful Swift snapshot testing.
https://www.pointfree.co/episodes/ep41-a-tour-of-snapshot-testing
MIT License
3.73k stars 568 forks source link

New lines cause JSON diffing to fail #415

Open lukeredpath opened 3 years ago

lukeredpath commented 3 years ago

I'm trying to use the json snapshotting strategy to test my app's Codable types but I'm hitting an issue with new lines in the file causing the diffing to fail.

I have a nice little TDD strategy for new types:

  1. Add type and Codable conformance
  2. Add snapshot test and run it to generate JSON file, re-run to check it passes
  3. Edit JSON file and change any default keys or values so they match what my API expects.
  4. Run the test as I make changes to my implementation until the test passes again.

The problem is that the generated file appears to have no new line characters and as soon as you save the JSON file (I've tried in Xcode and Vim) a new line character gets added that causes the test to fail.

I'm not sure of the best solution to this - I guess it would either involve explicitly inserting a new line character when saving the JSON file or stripping any trailing newlines before diffing.

lukeredpath commented 3 years ago

As a workaround, appending a new line character does seem to solve the problem for me:

extension Snapshotting where Value: Encodable, Format == String {
  /// A snapshot strategy for comparing encodable structures based on their JSON representation.
  ///
  /// - Parameter encoder: A JSON encoder.
  public static func newlineJson(_ encoder: JSONEncoder) -> Snapshotting {
    var snapshotting = SimplySnapshotting.lines.pullback { (encodable: Value) in
      try! String(decoding: encoder.encode(encodable), as: UTF8.self) + "\n"
    }
    snapshotting.pathExtension = "json"
    return snapshotting
  }
}