1

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

3
  • Would help to have a sample output added to the question and mention what are you trying to test in that sample. Commented Jun 13, 2023 at 14:14
  • @MuhammadTashfeen I have added a simple example output Commented Jun 13, 2023 at 14:40
  • I believe you can test it using $response->assertJsonFragment(['id' => 46]);. I haven't tested it but I believe it should work. Let me know. Commented Jun 13, 2023 at 15:43

1 Answer 1

2

Because your response is an array it will be prefixed with and index (just like a nested array). So simply use the index of the element you want to access. In your case it would be something like this:

 $response->assertJson(fn (AssertableJson $json) =>
        $json->has(3)
             ->has('2', fn (AssertableJson $json) =>
                //assert something inside 2nd element in array
                 $json->where('first_name', 'Emma')
                      ->etc()
             )
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! I was looking exactly for this - struggled to find the syntax, but this is it!

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.