Skip to content

Commit 9053103

Browse files
committed
Added ability to simulate "withCredentials" in test requests
1 parent 7cf519a commit 9053103

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

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

Lines changed: 37 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 behave like
58+
* the XHR withCredentials-flag was set.
59+
* @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
60+
*
61+
* @var bool
62+
*/
63+
protected $withCredentials;
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 in 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,8 @@ 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, $uri, [], $this->prepareCookiesForJsonRequest(),
474+
$files, $this->transformHeadersToServerVars($headers), $content
453475
);
454476
}
455477

@@ -577,6 +599,20 @@ protected function prepareCookiesForRequest()
577599
})->merge($this->unencryptedCookies)->all();
578600
}
579601

602+
/**
603+
* If enabled, add cookies for Json requests.
604+
*
605+
* @return array
606+
*/
607+
protected function prepareCookiesForJsonRequest()
608+
{
609+
if ($this->withCredentials) {
610+
return $this->prepareCookiesForRequest();
611+
} else {
612+
return [];
613+
}
614+
}
615+
580616
/**
581617
* Follow a redirect chain until a non-redirect is received.
582618
*

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)