Testing Cookie Modification in Laravel 8
If there’s a better way to pass a cookie from one request to another, in a phpunit feature test in Laravel, please let me know! Here’s one way to handle it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php namespace Tests\Feature; use Illuminate\Cookie\CookieValuePrefix; use Tests\TestCase; class DiveDeeperTest extends TestCase { /** * Tests if the diveDeeper route appends the passed value to the cookie arr. * @return void */ public function test_it_updates_path_cookie() { // Post a deeperPath to the diveDeeper route (with a starter cookie). // This should append the "deeperPath" value to the "path" cookie array. $resp = $this->withCookie('path', serialize(['/'])) ->post(route('diveDeeper'), [ 'deeperPath' => 'Users' ]); // Assert that the cookie has been modified. $resp->assertCookie('path', serialize(['/', 'Users'])); // If we make another post request here, it won't include our // modified "path" cookie. We have to retrieve it, then pass it // through to the next request. // Decrypt the cookie (now modified by the diveDeeper route). $cookieValue = CookieValuePrefix::remove(app('encrypter') ->decrypt($resp->getCookie('path')->getValue(), false)); // Hit the diveDeeper route again using the modified cookie value. $resp = $this->withCookie('path', $cookieValue) ->post(route('diveDeeper'), [ 'deeperPath' => 'adam' ]); // Assert that the cookie has been modified again. $resp->assertCookie('path', serialize(['/', 'Users', 'adam'])); // Etc... } } |