How to use Laravel AssertJson for testing a structured response

164 Views Asked by At

I have a signup API that returns a JSON response in this kind of format

{
    "meta": {
        //response metadata
    },
    "data": {
        //user object
    }
}

I want to test this response with AssertableJson but I'm only concerned about the user object.

How do I use AssertableJson only for the data property of the response?

I've tried something like this with no success

$response->data->assertJson(
            function(AssertableJson $json){
                $json->whereType('id', 'string')
                     ->where('email', '[email protected]')
                     ->etc();
            }
        );
1

There are 1 best solutions below

0
Marsel.V On

You should use has to tell Laravel to look at the data key, and don't forget to use etc() doc

etc() allows an object to have additional keys not specified in the assert

$response->data->assertJson(fn (AssertableJson $json) =>
   $json->has('data', fn (AssertableJson $data) =>
      $data->whereType('id', 'string')
           ->where('email', '[email protected]')
           ->etc()
   )->etc()
);