diff --git a/src/Tempest/Framework/Testing/Http/TestResponseHelper.php b/src/Tempest/Framework/Testing/Http/TestResponseHelper.php index 7915e7d04..497669ed0 100644 --- a/src/Tempest/Framework/Testing/Http/TestResponseHelper.php +++ b/src/Tempest/Framework/Testing/Http/TestResponseHelper.php @@ -554,6 +554,54 @@ public function assertJson(array $expected = []): self return $this; } + /** + * Assert that the JSON response contains the given subset. + * + * The keys can also be specified using dot notation. + * + * ### Example + * ``` + * // using dot notation + * $this->http->get(uri([BookController::class, 'index'])) + * ->assertJsonSubset([ + * 'id' => 1, + * 'title' => 'Timeline Taxi', + * 'author.name' => 'Brent', + * ]); + * + * // using nested arrays + * $this->http->get(uri([BookController::class, 'index'])) + * ->assertJsonSubset([ + * 'id' => 1, + * 'title' => 'Timeline Taxi', + * 'author' => [ + * 'name' => 'Brent', + * ], + * ]); + * ``` + * + * @param array $expected + */ + public function assertJsonSubset(array $expected): self + { + $expected = arr($expected)->undot()->dot()->toArray(); + $actual = arr($this->response->body)->dot()->toArray(); + + foreach ($expected as $key => $value) { + Assert::assertArrayHasKey( + key: $key, + array: $actual, + ); + + Assert::assertEquals( + expected: $value, + actual: $actual[$key], + ); + } + + return $this; + } + /** * Asserts the response contains the given keys. * diff --git a/tests/Integration/Testing/Http/TestResponseHelperTest.php b/tests/Integration/Testing/Http/TestResponseHelperTest.php index a65f8400c..0ffa0ef1f 100644 --- a/tests/Integration/Testing/Http/TestResponseHelperTest.php +++ b/tests/Integration/Testing/Http/TestResponseHelperTest.php @@ -226,6 +226,17 @@ public function test_assert_json(): void $helper->assertJson(['title' => 'Timeline Taxi', 'author.name' => 'John']); } + public function test_assert_json_subset(): void + { + $helper = new TestResponseHelper( + new GenericResponse(status: Status::OK, body: ['title' => 'Timeline Taxi', 'author' => ['name' => 'John', 'country' => 'NL']]), + new GenericRequest(Method::GET, '/'), + ); + + $helper->assertJsonSubset(['title' => 'Timeline Taxi', 'author' => ['country' => 'NL']]); + $helper->assertJsonSubset(['title' => 'Timeline Taxi', 'author.country' => 'NL']); + } + public static function provide_assert_status_cases(): iterable { return [