Courses

Testing in Laravel 11: Advanced Level

Asserting JSON Structure

Summary of this lesson:
- Test JSON response structures
- Use assertJsonFragment() and assertJsonCount()
- Implement fluent JSON testing
- Check JSON paths and structures
- Compare different JSON assertion methods

In the Testing For Beginners course, we tested that the response is JSON. However, you might need to test the JSON structure more deeply when creating APIs. Let's see how we can do it.


Laravel Code

In this example, we have a route in routes/api.php and a CRUD Controller. However, the products list is returned using the API Resource, and not all fields are returned deliberately for this example.

routes/api.php:

use App\Http\Controllers\Api\ProductController;
 
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
 
Route::apiResource('products', ProductController::class);

app/Http/Controllers/Api/ProductController.php:

use App\Models\Product;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
 
class ProductController extends Controller
{
public function index(): JsonResource
{
return ProductResource::collection(Product::all());
}
 
public function show(Product $product): JsonResource
{
return ProductResource::make($product);
}
 
public function update(Request $request, Product $product): JsonResource
{
$product->update($request->all());
 
return ProductResource::make($product);
}
}

app/Http/Resources/ProductResource.php:

class ProductResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}

When we test the /api/products endpoint using the API client, we will get a list of products from the DB.


JSON Data Anywhere & JSON Count

Using the assertJsonFragment(), you can test whether the response contains...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord