Reputation: 6007
In my Laravel project I want to test a JSON response what is acually a paginator result with data
key. It's an array and it contains some elements. We don't know the amount exactly, because it's coming from a function.
My problem is if the pagination limit is 10 and I change the elements number over the pagination limit, for example 20, I still get back 10 elements only. But I want to test it too.
Now I have this code:
$response
->assertSuccessful()
->assertJson(function (AssertableJson $json) use ($allElementsCount) {
$json
->has('data')
->whereType('data', 'array')
// here I want to test the count of 'data' array
->etc();
});
How can I test an array count in a JSON response?
Upvotes: 4
Views: 5115
Reputation: 3388
I usually use
$reponse->assertJson(fn (AssertableJson $json) => $json
->has('data', 10); // expect data has 10 items
->count('data', 10) // this also works, but I don't use this for no reason
// and while at it, this is my way to make sure the order is correct
->where('data.0.id', $items[0]->id)
->where('data.1.id', $items[1]->id)
);
If only 1 item is expected
$reponse->assertJson(fn (AssertableJson $json) => $json
// expect data has 1 item, and has these attributes
->has('data', 1, fn (AssertableJson $json) => $json
->where('id', $item->id)
->where('name', $item->name)
)
);
Upvotes: 1