8000 [BrowserKit] Add jsonRequest function to the browser-kit client · symfony/symfony@c2fa2cb · GitHub
[go: up one dir, main page]

Skip to content

Commit c2fa2cb

Browse files
alexander-schranzchalasr
authored andcommitted
[BrowserKit] Add jsonRequest function to the browser-kit client
1 parent abbb3d0 commit c2fa2cb

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/Symfony/Component/BrowserKit/AbstractBrowser.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,24 @@ public function xmlHttpRequest(string $method, string $uri, array $parameters =
161161
}
162162
}
163163

164+
/**
165+
* Converts the request parameters into a JSON string and uses it as request content.
166+
*/
167+
public function jsonRequest(string $method, string $uri, array $parameters = [], array $server = [], bool $changeHistory = true): Crawler
168+
{
169+
$content = json_encode($parameters);
170+
171+
$this->setServerParameter('CONTENT_TYPE', 'application/json');
172+
$this->setServerParameter('HTTP_ACCEPT', 'application/json');
173+
174+
try {
175+
return $this->request($method, $uri, [], [], $server, $content, $changeHistory);
176+
} finally {
177+
unset($this->server['CONTENT_TYPE']);
178+
unset($this->server['HTTP_ACCEPT']);
179+
}
180+
}
181+
164182
/**
165183
* Returns the History instance.
166184
*

src/Symfony/Component/BrowserKit/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
5.3.0
5+
-----
6+
7+
* Added `jsonRequest` method to `AbstractBrowser`
8+
49
4.3.0
510
-----
611

src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@ public function testXmlHttpRequest()
6060
$this->assertFalse($client->getServerParameter('HTTP_X_REQUESTED_WITH', false));
6161
}
6262

63+
public function testJsonRequest()
64+
{
65+
$client = $this->getBrowser();
66+
$client->jsonRequest('GET', 'http://example.com/', ['param' => 1], [], true);
67+
$this->assertSame('application/json', $client->getRequest()->getServer()['CONTENT_TYPE']);
68+
$this->assertSame('application/json', $client->getRequest()->getServer()['HTTP_ACCEPT']);
69+
$this->assertFalse($client->getServerParameter('CONTENT_TYPE', false));
70+
$this->assertFalse($client->getServerParameter('HTTP_ACCEPT', false));
71+
$this->assertSame('{"param":1}', $client->getRequest()->getContent());
72+
}
73+
6374
public function testGetRequestWithIpAsHttpHost()
6475
{
6576
$client = $this->getBrowser();

0 commit comments

Comments
 (0)
0