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...