Cruorzy's avatar
Level 14

Simple blade layout test

So I installed a new Laravel app with Breeze and ran pest --coverage

And see that GuestLayout has 0% coverage. How do I simply go and test this one? I'm not really getting it I think.

GuestLayout.php

<?php

declare(strict_types=1);

namespace App\View\Components;

use Illuminate\View\Component;
use Illuminate\View\View;

final class GuestLayout extends Component
{
    /**
     * Get the view / contents that represents the component.
     */
    public function render(): View
    {
        return view('layouts.guest');
    }
}

guest.blade.php

GuestLayoutTest.php

<?php

declare(strict_types=1);

use App\View\Components\GuestLayout;

it('renders the guest layout', function () {

    $this->component(GuestLayout::class);

});

Results in the following error Undefined variable $slot (View: C:\Users\User\Herd\project\resources\views\layouts\guest.blade.php)

0 likes
1 reply
LaryAI's avatar
Level 58

The error you're encountering, Undefined variable $slot, occurs because the Blade component system expects a $slot variable to be passed to the view when using components. This variable represents the content that will be injected into the component's layout.

To test the GuestLayout component properly, you need to ensure that the $slot variable is defined when rendering the component in your test. Here's how you can modify your test to include the $slot:

<?php

declare(strict_types=1);

use App\View\Components\GuestLayout;
use Illuminate\Support\Facades\View;

it('renders the guest layout', function () {
    // Define the content for the slot
    $slotContent = 'Test content';

    // Render the component with the slot content
    $view = $this->component(GuestLayout::class, [], ['slot' => $slotContent]);

    // Assert that the rendered view contains the slot content
    $view->assertSee($slotContent);
});

Explanation:

  1. Slot Content: We define a $slotContent variable to simulate the content that would be passed to the component in a real application.

  2. Render Component: We use the component method to render the GuestLayout component. The third parameter of this method is an array of data to pass to the view, where we specify the slot key with our $slotContent.

  3. Assertion: We use assertSee to check that the rendered view contains the content we passed to the slot, ensuring that the component renders correctly.

This approach should resolve the error and allow you to test the GuestLayout component effectively.

Please or to participate in this conversation.