
Testing Partial JSON Responses with Laravel
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.
Here is a quick example to show how this can work. Let’s say your app has a way to fetch information on a specific user:
Route::get('/api/users', function() {
return App\User::all();
});
This returns the JSON for all the users:
// /api/user/
[
{"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"},
{"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"}
]
Now with the new assertJsonFrament
you can test it like this:
/** @test */
function test_json_response()
{
$response = $this->json('GET', '/api/user/1');
$response
->assertStatus(200)
->assertJsonFragment([
'name' => 'Bill Murray',
]);
}
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: Laravel 5.4 / Testing
Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.
No Spam, ever. We'll never share your email address and you can opt out at any time.
Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.
Laravel Jobs

- Laravel Developer
-
San Jose, CA - Must Be Local
X3 Builders - Experienced PHP Developer
-
Wilmington, NC
Queensboro Shirt Company - Senior Laravel developer
-
Netherlands, Rotterdam
Pionect - Senior Laravel Engineer
-
Remote okay (must already live in USA)
Hawthorne Effect - Senior Software Engineer (Remote - Contract)
-
Remote
Koodi Systems - PHP Developer
-
Pittsburgh / Remote
Sequoia Waste Solutions - Software Developer
-
Eindhoven
Simac IDS
Request Object Changes in Lumen 5.4
A couple of weeks ago the Lumen core team managed to fix an issue with the request object when being called in unit t…
Review: Refactoring to Collections
“Never write another loop again.” A strong promo sentence used by Adam Wathan to market his Refactoring to Collection…