Passing on Cookies with Testing in Laravel – PHPUnit Testing

When testing with Laravel, cookies are reset on the next request.

To circumvent this, you can grab the cookie and insert it into the next request.

Like:

public function test_cookies_with_multiple_requests(): void
    {

        $response = $this->get('/page-with-cookies');
        $response->assertStatus(200);

        // Verify that the cookie with COOKIENAME exists
        $response->assertCookie("COOKIENAME");

        $newWesponse = $this->withCookies([
            'COOKIENAME' => $response->getCookie("COOKIENAME")->getValue()
        ])->get('/page-with-cookies');

        $response->assertStatus(200);

        // You can check the value from the cookie name here:
        // $response->assertCookie("COOKIENAME", "should contain this value");
    }

Thanks to this blog for helping me solve this.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top