首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在功能测试中使用ajax提交表单

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

Stack Overflow用户
提问于 2015-04-29 22:56:52
回答 2查看 2.4K关注 0票数 4

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

看起来提交方法没有使用一个参数来指定它是否是ajax --这与请求方法-> 提交不同

谢谢

UPDATE1

代码语言:javascript
复制
////////////////////////////////////////////////
// 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')
);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-30 03:49:27

请求头中的Symfony 请求对象拦截XmlHttpRequest。因此,只需将正确的标题添加到测试类中的请求中,例如:

代码语言:javascript
复制
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',
        )
    );
}

希望能帮上忙

票数 7
EN

Stack Overflow用户

发布于 2016-10-26 09:14:40

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

代码语言:javascript
复制
$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');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29956053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档