在功能测试中使用 ajax 提交表单

submit a form using ajax in functional test

我正在为我的项目的题词部分创建一个功能测试,如果表单需要进入 ajax 请求,我需要知道如何测试它,否则服务器将始终 return 一个空的铭文表格。

看起来 submit 方法不接受一个参数来指定它是否是一个 ajax 与请求方法不同的请求 -> http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Client.html#method_submit

谢谢

更新1

////////////////////////////////////////////////
// My functional test looks exactly like this //
////////////////////////////////////////////////
$form = $buttonCrawlerNode->form(array(
    'name'              => 'Fabien',
    'my_form[subject]'  => 'Symfony rocks!',
));
// There is no way here I can tell client to submit using ajax!!!!
$client->submit($form);

// Why can't we tell client to submit using ajax???
// Like we do here in the request méthod
$client->request(
    'GET',
    '/post/hello-world',
    array(),
    array(),
    array('HTTP_X-Requested-With' => 'XMLHttpRequest')
);

Symfony Request Object intercept an XmlHttpRequest 中的 header 请求。因此,只需在测试 class 中将正确的 header 添加到您的请求中,例如:

class FooFunctionalTest extends WebTestCase
{
    $client = static::CreateClient();
    $url = '/post/hello-world';
    // makes the POST request
    $crawler = $client->request('POST', $url, array(
        'my_form' => array(
            'subject' => 'Symfony rocks!'
        )),
        array(),
        array(
            'HTTP_X-Requested-With' => 'XMLHttpRequest',
        )
    );
}

希望对您有所帮助

实际上有一种方法可以利用 Client::submit,但是如果您想在此之后执行非 ajax 请求,则需要创建新的 Client 实例(目前,请参阅 GitHub 问题 link 下面)。

$client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
$client->submit($form);

// The following method doesn't exist yet.
// @see https://github.com/symfony/symfony/issues/20306
// If this method gets added then you won't need to create
// new Client instances for following non-ajax requests,
// you can just do this:
// $client->unsetServerParameter('HTTP_X-Requested-With');