pascalvgemert
pascalvgemert

Reputation: 1247

Why does Laravels assertJson fails when using has to check in root properties?

Given is the JSON return by the API call:

{
  "data": [
     { 
       "id": 1,
     }
  ],
  "meta" {
    "foo": "bar"
  },
  "links": {
    "self": "/"
  }

When executing the following code in the test of my API call:

$response
    ->assertOk()
    ->assertJson(fn (AssertableJson $json) =>
        $json
           ->has('data')
    );

My test fails with the following error:

Unexpected properties were found on the root level.
Failed asserting that two arrays are identical.

 --- Expected
 +++ Actual

 -Array &0 ()
 +Array &0 (
 +    1 => 'links'
 +    2 => 'meta'
 +)

Where I thought the assertion would only check if the 'data' key was present in the response.
When using $json->hasAll(['data', 'meta', 'links']) the test succeeds.

Upvotes: 0

Views: 1501

Answers (1)

AidOnline01
AidOnline01

Reputation: 737

By default laravel assertJson with callback function asserts exact match on json object. To avoid strict comparison, you need to use etc method.

Excerpt from documentation

Understanding The etc Method

In the example above, you may have noticed we invoked the etc method at the end of our assertion chain. This method informs Laravel that there may be other attributes present on the JSON object. If the etc method is not used, the test will fail if other attributes that you did not make assertions against exist on the JSON object.

The intention behind this behavior is to protect you from unintentionally exposing sensitive information in your JSON responses by forcing you to either explicitly make an assertion against the attribute or explicitly allow additional attributes via the etc method.

Upvotes: 2

Related Questions