Laravel provides many useful helpers for testing your application and it has great support for testing HTTP testing through its fluent API.
A feature added to v5.4.10 is a new assertJsonFragment
method that allows you to look for a specific fragment instead of the whole JSON response.
Laravel JSON response
Here is a quick example of a Laravel JSON response to show how this can work. Let’s say your app has a way to fetch information on a specific user:
1Route::get('/api/users', function() {2 return App\User::all();3});
This returns the JSON for all the users:
1// /api/user/2[3 {"id":1,"name":"Bill Murray","email":"bill.murray@example.org","created_at":"2017-02-14 01:53:04","updated_at":"2017-02-14 01:53:04"},4 {"id":2,"name":"John Doe","email":"john.doe@example.org","created_at":"2017-02-14 02:23:14","updated_at":"2017-02-14 02:23:14"}5]
Utilizing Laravel’s assertJsonFragment
Now with the new assertJsonFragment
you can test it like this:
1/** @test */ 2function test_json_response() 3{ 4 $response = $this->json('GET', '/api/user/1'); 5 6 $response 7 ->assertStatus(200) 8 ->assertJsonFragment([ 9 'name' => 'Bill Murray',10 ]);11}
This is just another small tool available in your arsenal to make testing easier. Check out the documentation for other methods of testing JSON responses.
Filed in: