Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match JsonStructure in PhpUnit Test - Laravel 5.4

I am creating a unit test and want to test the JSON structure returned in the response. I am aware that the TestResponse provides a method assertJsonStructure to match the structure of your JSON response. But for some reason I am unable to map the $structure to my response and in result the test fails. Let me share the required snippets.

Endpoint Response

{    "status": true,    "message": "",    "data": [        {           "id": 2,           "name": "Shanelle Goodwin",           "email": "[email protected]",           "created_at": "2017-03-05 16:12:49",           "updated_at": "2017-03-05 16:12:49",           "user_id": 1        }     ] } 

Test Function

public function testEndpoint(){    $response = $this->get('/api/manufacturer/read', [], $this->headers);   $response->assertStatus(200);   $response->assertJsonStructure([     'status',     'message',     'data' => [       {         'id',         'name',         'email',         'created_at',         'updated_at',         'user_id'       }     ]   ]);   var_dump("'/api/manufacturer/read' => Test Endpoint"); } 

There can multiple nodes in data array so that is why i tried to mention the array in structure but seems it doesn't map correctly.Any help would be appreciated :-)

like image 228
Farooq Ahmed Khan Avatar asked Mar 07 '17 20:03

Farooq Ahmed Khan


1 Answers

Luckily, playing with different options I have solved this issue. A '*' is expected as key if we are to match a nested object in an array. We can see the reference here.

Source: TestResponse

I have set the structure like this for array ofobjects`

$response->assertJsonStructure([     'status',     'message',     'data' => [       '*' => [         'id',         'name',         'email',         'created_at',         'updated_at',         'user_id'       ]     ]   ]); 

And if you want to match just a single object

$response->assertJsonStructure([     'status',     'message',     'data' => [       [         'id',         'name',         'email',         'created_at',         'updated_at',         'user_id'       ]     ]   ]); 
like image 149
Farooq Ahmed Khan Avatar answered Oct 02 '22 15:10

Farooq Ahmed Khan