Skip to content

Commit

Permalink
[9.x] Make assertPath() accepts Closure (#41409)
Browse files Browse the repository at this point in the history
* Make assertPath() accepts Closure

* Add tests
  • Loading branch information
villfa authored Mar 10, 2022
1 parent 70d992c commit f5fe63f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Illuminate/Testing/AssertableJsonString.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Testing;

use ArrayAccess;
use Closure;
use Countable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Arr;
Expand Down Expand Up @@ -219,7 +220,11 @@ public function assertMissingExact(array $data)
*/
public function assertPath($path, $expect)
{
PHPUnit::assertSame($expect, $this->json($path));
if ($expect instanceof Closure) {
PHPUnit::assertTrue($expect($this->json($path)));
} else {
PHPUnit::assertSame($expect, $this->json($path));
}

return $this;
}
Expand Down
21 changes: 21 additions & 0 deletions tests/Testing/TestResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,27 @@ public function testAssertJsonPathCanFail()
$response->assertJsonPath('0.id', '10');
}

public function testAssertJsonPathWithClosure()
{
$response = TestResponse::fromBaseResponse(new Response([
'data' => ['foo' => 'bar'],
]));

$response->assertJsonPath('data.foo', fn ($value) => $value === 'bar');
}

public function testAssertJsonPathWithClosureCanFail()
{
$response = TestResponse::fromBaseResponse(new Response([
'data' => ['foo' => 'bar'],
]));

$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('Failed asserting that false is true.');

$response->assertJsonPath('data.foo', fn ($value) => $value === null);
}

public function testAssertJsonFragment()
{
$response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub));
Expand Down

0 comments on commit f5fe63f

Please sign in to comment.