是否可以在symfony2测试中模拟/生成XMLHttpRequest请求(ajax)?
在使用“有问题”的答案进行搜索后,正确的语法是:
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
Request#isXmlHttpRequest()
方法只是检查X-Requested-With
头是否等于XMLHttpRequest
。如果这是您用来确定请求是否是ajax调用的方法,那么您可以通过向请求添加适当的标头来模拟测试客户端中的行为:
class FooFunctionalTest extends WebTestCase
{
$client = static::CreateClient();
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'X-Requested-With' => 'XMLHttpRequest',
));
// ...
}
有关Request对象in the source code的更多信息。
对于POST
,PUT
:
$crawler = $client->request('POST', '/foo/', array('param' => 'value'), array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
对于POST
,PUT
与原始JSON
身体:
$crawler = $client->request('POST', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
'CONTENT_TYPE' => 'application/json',
), '{"param": "value"}');
如果您正在使用Symfony 3.x或4.x,这是使用POST方法执行此操作的正确方法。
$data = ['some' => 'value'];
$client = static::createClient();
$client->request('POST', '/some_uri', ['data' => $data], [],; [
'HTTP_X-Requested-With' => 'XMLHttpRequest',
]);