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 :-)
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 of
objects`
$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' ] ] ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With