Testing Nested Component Error cannot get id of non object

What seems to be the problem: When i try test a livewire component it works 100% in the site but as soon as i write unit tests for it it keeps failing that it cannot get property id of non-object.

Steps to Reproduce:

Are you using the latest version of Livewire: Yes

Do you have any screenshots or code examples:

The parent component’s loop

@foreach($organisations as $index => $organisation)
     <tr>
         <td>{{ $organisation->name }}</td>
         <td>
             <x-html.status-badge :status="$organisation->status"/>
        </td>
        <td class="text-right">
            <livewire:organisations.grid-drop-menu :organisation="$organisation" :key="$loop->index"/>
        </td>
    </tr>
@endforeach

Nested Component Class

class GridDropMenu extends Component
{
    public Organisation $organisation;

    ....
}

Nested Component (it is a dropdown button with actions)

<x-input.dropdown-button :link="route('organisations.edit', ['id' => $organisation->id])" :action="trans('custom/actions.edit')">

    <x-slot name="icon">
        <x-feather-edit class="mr-2 mt-n1" height="16" width="16"/>
    </x-slot>

    <button class="dropdown-item" wire:click="deleteOrganisation">{{ __('custom/actions.delete') }}</button>

</x-input.dropdown-button>

UnitTest

public function can_suspend_organisation() 
{
    $user = User::factory()->create();

    $organisation = Organisation::find(1);

    Livewire::actingAs($user)
        ->test('organisations.grid-drop-menu', ['initialOrganisation' => $organisation])
        ->set('organisation', $organisation)
        ->call('deleteOrganisation')
        ->assertEmitted('organisationChanged');
}

even if i remove the initialOrganisation value it still gives the same error.

Error

ErrorException

Trying to get property 'id' of non-object (View: /resources/views/livewire/organisations/grid-drop-menu.blade.php) (View: /resources/views/livewire/organisations/grid-drop-menu.blade.php)

I made the nested component just to receive the :organisation, as im already looping through them instead of fetching the organisation again from the nested component or is there another way of doing this.

Thanks

did you find a resolution to this? I’ve run into the exact same thing where the attribute appears just fine in the browser but not in my test.

Hi
It was just a silly mistake on my end, you have to set your initial property in the test.

class GridDropMenu extends Component
{
    public Organisation $organisation;

    ....
}

->test('organisations.grid-drop-menu', ['organisation' => $organisation])

the it will set the value and it won’t give any non-object error.

This seems to have worked for me.

1 Like

thank you. That’s worked a charm.