Search code examples
laravelcookiesphpunitguzzle

How to fake cookie for HTTP fake respond?


I want to mock a HTTP response in Laravel with cookie. I tried this:

Http::fake([
    'my-mocked-route' => Http::response(['foo' => 'bar'], 200)->withCookie('a', 10),
]);

but I receive

Call to undefined method GuzzleHttp\Promise\FulfilledPromise::withCookie()

same if I just use cookie instead of withCookie. Also, I would to add Cookie attributes aswell.

I also tried

Http::fake([
     
        'qnnect' => Http::response(['foo' => 'bar'], 200, ['Cookie' => 'a=10; Expiration=Wed, 21 Oct 2015 07:28:00 GMT']),
    ]);

And although the response contains correct cookies in the header, $response->cookies() returns an empty CookieJar.

Is there a possibility to mock cookies in the respond?


Solution

  • The correct header is Set-Cookie and not Cookie. Domain is also required.

      Http::fake([
        'home' => Http::response('Ok', 200, ['Set-Cookie' => 'foo=bar; domain=.'])
      ]);
    
      $response = Http::get('home');
      dump($response->cookies()->getCookieByName('foo')->getValue());
    

    Output will be bar