在Symfony2中功能性地测试AJAX / XMLHttpRequest页面

问题描述 投票:15回答:4

是否可以在symfony2测试中模拟/生成XMLHttpRequest请求(ajax)?

ajax testing symfony
4个回答
35
投票

在使用“有问题”的答案进行搜索后,正确的语法是:

$crawler = $client->request('GET', '/foo/', array(), array(), array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
));

6
投票

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的更多信息。


2
投票

对于POSTPUT

$crawler = $client->request('POST', '/foo/', array('param' => 'value'), array(),
array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
));

对于POSTPUT与原始JSON身体:

$crawler = $client->request('POST', '/foo/', array(), array(), array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
    'CONTENT_TYPE' => 'application/json',
), '{"param": "value"}');

0
投票

如果您正在使用Symfony 3.x或4.x,这是使用POST方法执行此操作的正确方法。

$data = ['some' => 'value'];
$client = static::createClient();
$client->request('POST', '/some_uri', ['data' => $data], [],; [
  'HTTP_X-Requested-With' => 'XMLHttpRequest',
]);
© www.soinside.com 2019 - 2024. All rights reserved.