I had a need today for a Livewire component to set a cookie, and wanted to test that it was actually set correctly.
Livewire includes support for reading cookies, but not for writing them.
And unfortunately, the redirect helper method doesn’t include any way to set a cookie.
Thankfully, Laravel provides a Cookie::queue()
method that will attach set the cookie on the next outgoing response, and since Livewire method calls result in a HTTP response (unless you use the renderless attribute), the framework takes care of attaching the cookie for you:
Cookie::queue('name', 'value', $minutes);
However, I found it counterintuitive to test this behavior.
There is an assertCookie()
method available when testing the component, but it always fails because we’re testing a Livewire component, not a request, and so the framework doesn’t attach the queued cookie(s).
My solution: use Cookie::queued()
to retrieve the queued cookie, and then run assertions against that: