在Symfony2中测试AJAX/XMLHttpRequest页面的功能
是否可以在symfony2测试中模拟/发出XMLHttpRequest请求(ajax?请求#isXmlHttpRequest()方法只是检查在Symfony2中测试AJAX/XMLHttpRequest页面的功能,ajax,testing,symfony,Ajax,Testing,Symfony,是否可以在symfony2测试中模拟/发出XMLHttpRequest请求(ajax?请求#isXmlHttpRequest()方法只是检查X-request-With头是否等同于XMLHttpRequest。如果您使用这种方法来确定请求是否为ajax调用,那么您可以通过向请求添加适当的头来模拟测试客户端中的行为: class FooFunctionalTest extends WebTestCase { $client = static::CreateClient(); $cr
X-request-With
头是否等同于XMLHttpRequest
。如果您使用这种方法来确定请求是否为ajax调用,那么您可以通过向请求添加适当的头来模拟测试客户端中的行为:
class FooFunctionalTest extends WebTestCase
{
$client = static::CreateClient();
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'X-Requested-With' => 'XMLHttpRequest',
));
// ...
}
可以找到有关请求对象的更多信息。使用“有问题”答案搜索后,正确的语法是:
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
对于
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',
]);
语法问题,请看我的答案。谢谢()