2

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?

netdjw
  • 5,419
  • 21
  • 88
  • 162

2 Answers2

5

You can use

$response->assertJsonCount(10, 'data');

Reference

Professor
  • 858
  • 1
  • 9
  • 17
0

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)
   )
);
Christhofer Natalius
  • 2,727
  • 2
  • 30
  • 39