Skip to content

Commit 55d61dc

Browse files
NachoSotoniilohlin
authored andcommitted
Added Snapshotting.json for Any value (pointfreeco#552)
* Added `Snapshotting.json` for `Any` value Currently the only way to snapshot `Any` value is using `dump`. However, the format isn't always as readable as it can be. For data that can be encoded in JSON, this new overload provides a much more readable output. * Fixed macOS build `.sortedKeys` is only available from `macOS 10.13`. * Public extension
1 parent 296f504 commit 55d61dc

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

Sources/SnapshotTesting/Snapshotting/Any.swift

+18
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,24 @@ extension Snapshotting where Format == String {
77
}
88
}
99

10+
@available(macOS 10.13, *)
11+
extension Snapshotting where Format == String {
12+
/// A snapshot strategy for comparing any structure based on their JSON representation.
13+
public static var json: Snapshotting {
14+
let options: JSONSerialization.WritingOptions = [
15+
.prettyPrinted,
16+
.sortedKeys
17+
]
18+
19+
var snapshotting = SimplySnapshotting.lines.pullback { (data: Value) in
20+
try! String(decoding: JSONSerialization.data(withJSONObject: data,
21+
options: options), as: UTF8.self)
22+
}
23+
snapshotting.pathExtension = "json"
24+
return snapshotting
25+
}
26+
}
27+
1028
private func snap<T>(_ value: T, name: String? = nil, indent: Int = 0) -> String {
1129
let indentation = String(repeating: " ", count: indent)
1230
let mirror = Mirror(reflecting: value)

Tests/SnapshotTestingTests/SnapshotTestingTests.swift

+11
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,17 @@ final class SnapshotTestingTests: XCTestCase {
4343
""")
4444
}
4545

46+
@available(macOS 10.13, *)
47+
func testAnyAsJson() throws {
48+
struct User: Encodable { let id: Int, name: String, bio: String }
49+
let user = User(id: 1, name: "Blobby", bio: "Blobbed around the world.")
50+
51+
let data = try JSONEncoder().encode(user)
52+
let any = try JSONSerialization.jsonObject(with: data, options: [])
53+
54+
assertSnapshot(matching: any, as: .json)
55+
}
56+
4657
func testAnySnapshotStringConvertible() {
4758
assertSnapshot(matching: "a" as Character, as: .dump, named: "character")
4859
assertSnapshot(matching: Data("Hello, world!".utf8), as: .dump, named: "data")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"bio" : "Blobbed around the world.",
3+
"id" : 1,
4+
"name" : "Blobby"
5+
}

0 commit comments

Comments
 (0)