Skip to content

Commit 5a5c6a4

Browse files
committed
Merge branch 'allow-withCredentials-for-json-in-tests' into 7.x
2 parents 5b47c76 + aa17e75 commit 5a5c6a4

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ trait MakesHttpRequests
5353
*/
5454
protected $encryptCookies = true;
5555

56+
/**
57+
* Indicated whether JSON requests should be performed "with credentials" (cookies).
58+
*
59+
* @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
60+
*
61+
* @var bool
62+
*/
63+
protected $withCredentials = false;
64+
5665
/**
5766
* Define additional headers to be sent with the request.
5867
*
@@ -230,6 +239,18 @@ public function followingRedirects()
230239
return $this;
231240
}
232241

242+
/**
243+
* Include cookies and authorization headers for JSON requests.
244+
*
245+
* @return $this
246+
*/
247+
public function withCredentials()
248+
{
249+
$this->withCredentials = true;
250+
251+
return $this;
252+
}
253+
233254
/**
234255
* Disable automatic encryption of cookie values.
235256
*
@@ -449,7 +470,13 @@ public function json($method, $uri, array $data = [], array $headers = [])
449470
], $headers);
450471

451472
return $this->call(
452-
$method, $uri, [], [], $files, $this->transformHeadersToServerVars($headers), $content
473+
$method,
474+
$uri,
475+
[],
476+
$this->prepareCookiesForJsonRequest(),
477+
$files,
478+
$this->transformHeadersToServerVars($headers),
479+
$content
453480
);
454481
}
455482

@@ -577,6 +604,16 @@ protected function prepareCookiesForRequest()
577604
})->merge($this->unencryptedCookies)->all();
578605
}
579606

607+
/**
608+
* If enabled, add cookies for JSON requests.
609+
*
610+
* @return array
611+
*/
612+
protected function prepareCookiesForJsonRequest()
613+
{
614+
return $this->withCredentials ? $this->prepareCookiesForRequest() : [];
615+
}
616+
580617
/**
581618
* Follow a redirect chain until a non-redirect is received.
582619
*

tests/Foundation/Testing/Concerns/MakesHttpRequestsTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ public function testWithUnencryptedCookiesSetsCookiesAndOverwritesPreviousValues
103103
$this->assertSame('baz', $this->unencryptedCookies['foo']);
104104
$this->assertSame('new-value', $this->unencryptedCookies['new-cookie']);
105105
}
106+
107+
public function testWithoutAndWithCredentials()
108+
{
109+
$this->encryptCookies = false;
110+
111+
$this->assertSame([], $this->prepareCookiesForJsonRequest());
112+
113+
$this->withCredentials();
114+
$this->defaultCookies = ['foo' => 'bar'];
115+
$this->assertSame(['foo' => 'bar'], $this->prepareCookiesForJsonRequest());
116+
}
106117
}
107118

108119
class MyMiddleware

0 commit comments

Comments
 (0)