Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/Tempest/Framework/Testing/Http/TestResponseHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, mixed> $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.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/Integration/Testing/Http/TestResponseHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down