-
-
Save macbookandrew/2e2dfbc985c44bc988650f735bcdf68f to your computer and use it in GitHub Desktop.
Setting and Testing Cookies in a Livewire Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Livewire; | |
use Illuminate\Support\Facades\Cookie; | |
use Livewire\Component; | |
class MyComponent extends Component | |
{ | |
public function render() | |
{ | |
return view('my-component'); | |
} | |
public function rememberMe() | |
{ | |
Cookie::queue( | |
name: 'contactId', | |
value: 'my-contact-id', | |
minutes: 60 * 24 * 365, | |
path: '/', | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Feature\Livewire; | |
use App\Livewire\MyComponent; | |
use App\Models\User; | |
use Illuminate\Support\Facades\Cookie; | |
use Livewire\Livewire; | |
use Tests\TestCase; | |
class MyComponentTest extends TestCase | |
{ | |
public function testComponentSetsCookie() | |
{ | |
$user = User::factory()->create(); | |
Livewire::actingAs($user) | |
->test(MyComponent::class) | |
->call('rememberMe') | |
->assertCookie('contactId', $user->contact_id) // FAILs | |
->assertOk(); | |
// The assertCookie method exists on the testable livewire component, but always fails: | |
// because we’re testing a Livewire component and not an actual request, | |
// the framework doesn’t attach the queued cookie. | |
// So instead, use Cookie::queued() to read the queued cookie, and then run assertions against that: | |
$cookie = Cookie::queued( | |
key: 'contactId', | |
path: '/', | |
); | |
$this->assertEquals($user->contact_id, $cookie->getValue()); | |
$this->assertEquals(now()->addYear()->unix(), $cookie->getExpiresTime()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment