laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.69k stars 11.05k forks source link

Cannot use withCookies when making test JSON requests #32965

Closed zakini closed 4 years ago

zakini commented 4 years ago

Description:

Using withCookies() in a test when making a JSON request (getJson(), postJson(), etc.) does not send the cookies to the application.

Steps To Reproduce:

Add this route:

Route::get('/', function () {
    return response()->json(request()->cookie('foo'));
});

Add this test:

public function testCookies()
{
    $value = $this->withCookies(['foo' => 'bar'])
        ->get('/')
        ->json();
    $jsonValue = $this->withCookies(['foo' => 'bar'])
        ->getJson('/')
        ->json();

    $this->assertEquals($value, $jsonValue);
}

This test will fail: $value is 'bar' but $jsonValue is []


Looks like this is because json() doesn't call $this->prepareCookiesForRequest() like the non-JSON methods (get(), post(), etc.). I'm happy to add this in a PR, unless there's a reason not to add this?

driesvints commented 4 years ago

That's because you usually don't use cookies to make requests to JSON endpoints.

zakini commented 4 years ago

But it does happen. Case in point: Laravel Sanctum SPA auth.

If nothing else, shouldn't this be mentioned in the docs somewhere?