I have implemented an API endpoint which returns a JSON array, and I want to test the values in say the 2nd element. Here is an example output - in my real data each array element has more attributes. I want to test attributes on different elements in the array. For example I might want to test the first_name attribute on the 2nd element.
[
{ "id" 23, "first_name": "Geri"},
{ "id" 25, "first_name": "Emma"},
{ "id" 46, "first_name": "Mel"}
]
Laravel fluent JSON testing allows you to test the nth element in a nested array using the following syntax
$response->assertJson(fn (AssertableJson $json) =>
$json->has('users', 3)
->has('users.1', fn (AssertableJson $json) =>
...
But my array is the root of the response. I can test the count and first element as follows but can't work out how to test a different element
$response->assertJson(fn (AssertableJson $json) =>
$json->has(3)
->first(fn (AssertableJson $json) =>
...
Is there any way to test a specific element other than the first using the fluent approach? Thanks
$response->assertJsonFragment(['id' => 46]);. I haven't tested it but I believe it should work. Let me know.