create(); $this->postJson('/api/cart', ['product_id' => $product->id]) ->assertSuccessful() ->assertJsonFragment(['product_id' => $product->id, 'quantity' => 1]); }); test('adding a product creates a cart and returns cart items', function () { $product = Product::factory()->create(); $response = $this->postJson('/api/cart', ['product_id' => $product->id]); $response->assertSuccessful() ->assertJsonFragment(['product_id' => $product->id, 'quantity' => 1]); expect(Cart::count())->toBe(1); }); test('adding the same product increments quantity', function () { $product = Product::factory()->create(); $this->postJson('/api/cart', ['product_id' => $product->id]); $response = $this->postJson('/api/cart', ['product_id' => $product->id]); $response->assertSuccessful() ->assertJsonFragment(['product_id' => $product->id, 'quantity' => 2]); }); test('adding a non-existent product fails validation', function () { $this->postJson('/api/cart', ['product_id' => 9999]) ->assertUnprocessable(); }); test('updating a cart item changes its quantity', function () { $product = Product::factory()->create(); $cart = Cart::factory()->create(['user_id' => null]); $cart->products()->attach($product->id, ['quantity' => 1]); $response = $this->withSession(['cart_id' => $cart->id]) ->patchJson("/api/cart/{$product->id}", ['quantity' => 5]); $response->assertSuccessful() ->assertJsonFragment(['product_id' => $product->id, 'quantity' => 5]); }); test('removing a product detaches it from the cart', function () { $product = Product::factory()->create(); $cart = Cart::factory()->create(['user_id' => null]); $cart->products()->attach($product->id, ['quantity' => 2]); $response = $this->withSession(['cart_id' => $cart->id]) ->deleteJson("/api/cart/{$product->id}"); $response->assertSuccessful() ->assertJsonMissing(['product_id' => $product->id]); expect($cart->fresh()->products)->toHaveCount(0); }); test('a cart can optionally belong to a user', function () { $user = User::factory()->create(); $cartWithUser = Cart::factory()->create(['user_id' => $user->id]); $cartGuest = Cart::factory()->create(['user_id' => null]); expect($cartWithUser->user)->toBeInstanceOf(User::class); expect($cartGuest->user)->toBeNull(); });