Skip to content

Commit cdb05c5

Browse files
authored
[8.x] Add AssertableJson::hasAny (#39265)
* Add `AssertableJson::hasAny` * Fix PHP7.3 compatibility * Fix syntax
1 parent 2c7260d commit cdb05c5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/Illuminate/Testing/Fluent/Concerns/Has.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,28 @@ public function hasAll($key): self
108108
return $this;
109109
}
110110

111+
/**
112+
* Assert that at least one of the given props exists.
113+
*
114+
* @param array|string $key
115+
* @return $this
116+
*/
117+
public function hasAny($key): self
118+
{
119+
$keys = is_array($key) ? $key : func_get_args();
120+
121+
PHPUnit::assertTrue(
122+
Arr::hasAny($this->prop(), $keys),
123+
sprintf('None of properties [%s] exist.', implode(', ', $keys))
124+
);
125+
126+
foreach ($keys as $key) {
127+
$this->interactsWith($key);
128+
}
129+
130+
return $this;
131+
}
132+
111133
/**
112134
* Assert that none of the given props exist.
113135
*

tests/Testing/TestResponseTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,29 @@ public function testAssertJsonWithFluentSkipsInteractionWhenTopLevelKeysNonAssoc
718718
});
719719
}
720720

721+
public function testAssertJsonWithFluentHasAnyThrows()
722+
{
723+
$response = TestResponse::fromBaseResponse(new Response([]));
724+
725+
$this->expectException(AssertionFailedError::class);
726+
$this->expectExceptionMessage('None of properties [data, errors, meta] exist.');
727+
728+
$response->assertJson(function (AssertableJson $json) {
729+
$json->hasAny('data', 'errors', 'meta');
730+
});
731+
}
732+
733+
public function testAssertJsonWithFluentHasAnyPasses()
734+
{
735+
$response = TestResponse::fromBaseResponse(new Response([
736+
'data' => [],
737+
]));
738+
739+
$response->assertJson(function (AssertableJson $json) {
740+
$json->hasAny('data', 'errors', 'meta');
741+
});
742+
}
743+
721744
public function testAssertSimilarJsonWithMixed()
722745
{
723746
$response = TestResponse::fromBaseResponse(new Response(new JsonSerializableMixedResourcesStub));

0 commit comments

Comments
 (0)