How to use Laravel’s fluent json assertions effectively
Introduction
Laravel offers many json testing methods but recently brought out a fluent way to test JSON responses. We need to pass a closure to the assertJson
method, which can then be used to make assertions against attributes of the json.
Fluent JSON allows us to target certain aspects of a JSON response more specifically than some traditional testing methods such as assertJsonFragment
or assertJsonMissing
.
Example
Say we have an endpoint which returns a specific vehicle
object, we could write a test in this form:
public function test_fluent_json()
{ $response = $this->getJson('/vehicles/1'); $response
->assertJson(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', 'Model T')
->missing('new')
->etc()
);}
This will check that the item returned has id
equal to ‘1’, name
equal to ‘Model T’, with no property called ‘new’ and the test will ignore if there are any other properties. We will look at how this is works below.
Useful methods
has
method
The ‘has’ method allows us to assert that an attribute is present in the JSON response.
Assert a response has the key description
:
$response->assertJson(fn (AssertableJson $json) => $json->has('description'););
Assert a response has 3 objects:
$response->assertJson(fn (AssertableJson $json) => $json->has(3););
Assert the response has an array with 4 items called vehicles
, where the first item has id
‘5’ and name
‘Model S’:
$response->assertJson(fn (AssertableJson $json) => $json->has('vehicles', 3)
->has('vehicle.0', fn ($json) =>
$json->where('id', 5)
->where('name', 'Model S')
));
missing
method
The missing method allows us to check that the property does NOT exist — such as a user’s password.
etc
method
By default, if you return more json in your response object than in your test, your test will fail. This makes sense as there may be sensitive information returned in your response that your test will not cover. However, if we only care about a few properties then we can use the etc
method to disable the check for ‘all properties’ on that json object, allowing the test to pass without having to test for every property.
Conclusion
It’s always important to test your api thoroughly and for this purpose Laravel provides some neat ways to test your JSON responses. Releasing fluent JSON has allowed more flexible testing, allowing data to be accessed as array variables on the JSON response.