# Component Guide: Blade View Components Blade View Components cho phép tái sử dụng giao diện UI kèm theo logic tính toán PHP đóng gói bên trong class component. --- ## 1. Bản Chất Kiểm Thử View Component Laravel cung cấp helper `$this->component(MyComponent::class, $data)` để render component ra chuỗi HTML trực tiếp trong môi trường test mà không cần khởi động trình duyệt. - **Cần test**: - Class constructor gán đúng thuộc tính (Props). - Thuộc tính mặc định khi không truyền vào. - Các method helper của Component tính toán đúng CSS class hoặc style. - HTML được render ra có chứa đúng nội dung, text, slot hoặc icon. --- ## 2. Mã Mẫu Chuẩn: View Component Test ### Component Nguồn: `App\View\Components\Alert` ```php namespace App\View\Components; use Illuminate\View\Component; use Illuminate\View\View; class Alert extends Component { public function __construct( public readonly string $type = 'info', public readonly ?string $title = null ) {} public function alertClass(): string { return match ($this->type) { 'success' => 'bg-green-100 text-green-800 border-green-300', 'error' => 'bg-red-100 text-red-800 border-red-300', default => 'bg-blue-100 text-blue-800 border-blue-300', }; } public function render(): View { return view('components.alert'); } } ``` ### Test Chuẩn: PHPUnit 10+ ```php namespace Tests\Unit\View\Components; use Tests\TestCase; use PHPUnit\Framework\Attributes\Test; use App\View\Components\Alert; class AlertTest extends TestCase { #[Test] public function it_calculates_correct_css_class_based_on_type(): void { $infoAlert = new Alert(type: 'info'); $this->assertStringContainsString('bg-blue-100', $infoAlert->alertClass()); $successAlert = new Alert(type: 'success'); $this->assertStringContainsString('bg-green-100', $successAlert->alertClass()); $errorAlert = new Alert(type: 'error'); $this->assertStringContainsString('bg-red-100', $errorAlert->alertClass()); } #[Test] public function it_renders_component_with_slot_content(): void { $view = $this->blade( 'Nội dung thông báo lưu thành công.' ); $view->assertSee('Thành công!'); $view->assertSee('Nội dung thông báo lưu thành công.'); $view->assertSee('bg-green-100'); } } ```