4

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?

2 Answers 2

6

You can use

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

Reference

Sign up to request clarification or add additional context in comments.

Comments

1

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)
   )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.