From da20a62e49180c579c1006ed56005dffe17c6b6e Mon Sep 17 00:00:00 2001 From: Mark Huot Date: Tue, 21 Nov 2023 22:56:21 -0500 Subject: [PATCH 1/2] Add toSnapshot() early return Sometimes objects need native toString() and toArray() methods that are different from what you want to snapshot. This adds an explicit toSnapshot() method that will be called first (when set) allowing for better snapshot values than the generic methods offer. --- src/Mixins/Expectation.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Mixins/Expectation.php b/src/Mixins/Expectation.php index a6910b64..a9edcf07 100644 --- a/src/Mixins/Expectation.php +++ b/src/Mixins/Expectation.php @@ -844,6 +844,7 @@ final class Expectation $string = match (true) { is_string($this->value) => $this->value, + is_object($this->value) && method_exists($this->value, 'toSnapshot') => $this->value->toSnapshot(), is_object($this->value) && method_exists($this->value, '__toString') => $this->value->__toString(), is_object($this->value) && method_exists($this->value, 'toString') => $this->value->toString(), $this->value instanceof \Illuminate\Testing\TestResponse => $this->value->getContent(), // @phpstan-ignore-line From 2a54b5819d5583698ba53e87d3d0bfa33fa1b2c8 Mon Sep 17 00:00:00 2001 From: markhuot Date: Tue, 28 Nov 2023 20:59:45 -0500 Subject: [PATCH 2/2] #1017 adds early return toSnapshot test --- .../pass_with__toSnapshot_.snap | 3 +++ tests/Features/Expect/toMatchSnapshot.php | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 tests/.pest/snapshots/Features/Expect/toMatchSnapshot/pass_with__toSnapshot_.snap diff --git a/tests/.pest/snapshots/Features/Expect/toMatchSnapshot/pass_with__toSnapshot_.snap b/tests/.pest/snapshots/Features/Expect/toMatchSnapshot/pass_with__toSnapshot_.snap new file mode 100644 index 00000000..afd4f5f9 --- /dev/null +++ b/tests/.pest/snapshots/Features/Expect/toMatchSnapshot/pass_with__toSnapshot_.snap @@ -0,0 +1,3 @@ +{ + "key": "
\n
\n
\n

Snapshot<\/h1>\n <\/div>\n <\/div>\n <\/div>" +} \ No newline at end of file diff --git a/tests/Features/Expect/toMatchSnapshot.php b/tests/Features/Expect/toMatchSnapshot.php index ed5c8458..8196cc0b 100644 --- a/tests/Features/Expect/toMatchSnapshot.php +++ b/tests/Features/Expect/toMatchSnapshot.php @@ -103,6 +103,26 @@ test('pass with array', function () { ])->toMatchSnapshot(); }); +test('pass with `toSnapshot`', function () { + TestSuite::getInstance()->snapshots->save(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT)); + + $object = new class($this->snapshotable) + { + public function __construct(protected string $snapshotable) + { + } + + public function toSnapshot() + { + return json_encode([ + 'key' => $this->snapshotable, + ], JSON_PRETTY_PRINT); + } + }; + + expect($object)->toMatchSnapshot(); +}); + test('failures', function () { TestSuite::getInstance()->snapshots->save($this->snapshotable);