【问题标题】:submit a form using ajax in functional test在功能测试中使用 ajax 提交表单
【发布时间】:2015-07-09 11:11:18
【问题描述】:

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

看起来提交方法没有参数来指定它是否是一个 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')
);

【问题讨论】:

  • 能否提供你的测试主题代码和单元测试代码?
  • 您可以执行 POST(第一个参数)并将底层数据作为数组(第三个参数)传递。你觉得这有什么问题?
  • 我编辑我的答案,希望这更清楚

标签: php ajax symfony phpunit functional-testing


【解决方案1】:

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

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',
        )
    );
}

希望有帮助

【讨论】:

  • 我已经更新了我的帖子,我可以通过提交方法添加标题吗?请看一下我帖子update1的cmets
  • 所以您确认我们不能利用 client->submit($form) 来处理 cookie 和所有内容。 结论 使用ajax发送表单,Client的提交方法做不到,所以我们只好使用经典请求。谢谢马特奥
  • @smarber 实际上你可以利用 client->submit($form)。看我的回答。
【解决方案2】:

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

$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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2011-11-28
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多