How do you test the return value of a function?

Lets assume I have a component with the function myFunction which returns a bool:

$component = Livewire::test(MyComponent::class);

$response = $component->call('myFunction');

How do you test that myFunction returns the expected value, as in the above $response is not a bool but the $component instance.

I couldn’t find anything for this in the docs either, but looking through the TestableLivewire class, there is an attribute called $lastResponse, which includes the return value of methods called.

It’s a bit clumsy, but you could do the following:

$component = Livewire::test(MyComponent::class)->call('myFunction');
$response = json_decode($component->lastResponse->content())
                       ->effects
                       ->returns
                       ->myFunction;
$this->assertTrue($response);

Alternatively you could make a mixin for the test component:

class LivewireTestMixin
{
    public function assertReturnEquals(): \Closure
    {
        return function(string $method, $expected, $message = '') {
            $jsonResponse = json_decode($this->lastResponse->content());
            $actual = $jsonResponse->effects->returns->$method;
            PHPUnit::assertEquals($expected, $actual, $message);

            return $this;
        };
    }
}

Then in your test:

\Livewire\Testing\TestableLivewire::mixin(new LivewireTestMixin());
Livewire::test(MyComponent::class)
   ->call('myFunction')
   ->assertReturnEquals('myFunction', true);

I do wonder if I haven’t missed something that already exists though…

In Livewire v3, instead of using the $componet->lastResponse->content() as stated by Alex, you should use $component->__get('effects')['return']. This will give you an array of values returned by the Livewire function.