Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test array in AssertableJson in Laravel 8?

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?

like image 477
netdjw Avatar asked Oct 22 '25 07:10

netdjw


2 Answers

You can use

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

Reference

like image 106
Professor Avatar answered Oct 25 '25 00:10

Professor


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)
   )
);
like image 45
Christhofer Natalius Avatar answered Oct 25 '25 01:10

Christhofer Natalius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!