Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Benko's avatar
Level 6

Problem with API tests

So, I have an API that returns JSON like so:

"data": [
{
"name": "United Kingdom",
"abbreviation": "UK"
},
{
"name": "United States",
"abbreviation": "US"
},
{
"name": "Australia",
"abbreviation": "AU"
}
]

And I tried to write a test for it. My code is now like this:

<?php

namespace Tests\Feature;

use Tests\DatabaseTestCase;
use App\Countries\Country;

use App\Http\Resources\CountryResource;

class CountryTest extends DatabaseTestCase {
    /** @test */
    public function it_can_retrieve_a_list_of_countries() {
        $country = Country::create([
            'name' => 'United Kingdom',
            'abbreviation' => 'UK'
        ]);

        $response = $this->json('GET', route('countries.index'), ['data' => $country->toArray()]);

        $response->assertJson([
            'name' => $country->name,
            'abbreviation' => $country->abbreviation
        ]);
    }
}

But the test keeps on failing with the following error:

There was 1 failure:

1) Tests\Feature\CountryTest::it_can_retrieve_a_list_of_countries
Unable to find JSON:

[{
    "name": "United Kingdom",
    "abbreviation": "UK"
}]

within response JSON:

[{
    "data": [
        {
            "name": "United Kingdom",
            "abbreviation": "UK"
        }
    ]
}].


Failed asserting that an array has the subset Array &0 (
    'name' => 'United Kingdom'
    'abbreviation' => 'UK'
).
--- Expected
+++ Actual
@@ @@
       'abbreviation' => 'UK',
     ),
   ),
-  'name' => 'United Kingdom',
-  'abbreviation' => 'UK',
 )

Does anybody know where the issue is? Thanks.

0 likes
3 replies
Sergiu17's avatar

Hi, as I see, your data is wrapped inside data, your assertion is for one element inside data

$response = $this->json('GET', route('countries.index'), ['data' => $country->toArray()]);

$response->assertJson([
    'data' => [
        'name' => $country->name,
        'abbreviation' => $country->abbreviation
    ]
]);

Try this, may work

Benko's avatar
Level 6

Sorry, I'm afraid that didn't work:

It treated data as a JSON object, rather than an array. I don't know how to put an array in there.

Talinon's avatar

Try this


$response->assertJson([
    'data' => [
        $country->only(['name', 'abbreviation'])
    ]
]);


Please or to participate in this conversation.