使用客户端或爬虫在phpunit / symfony中测试AJAX调用

问题描述 投票:0回答:1

我想测试一个控制器,它生成一个页面,其中的字段随ajax动态变化。

这是ajax的代码:

<script>
  var $groupeCompetence = $('#requete_prestataire_groupeCompetence');
// When sport gets selected ...
$groupeCompetence.change(function() {
  // ... retrieve the corresponding form.
  var $form = $(this).closest('form');
  // Simulate form data, but only include the selected sport value.
  var data = {};
  data[$groupeCompetence.attr('name')] = $groupeCompetence.val();
  // Submit data via AJAX to the form's action path.
  $.ajax({
    url : $form.attr('action'),
    type: $form.attr('method'),
    data : data,
    success: function(html) {
      // Replace current position field ...
      $('#requete_prestataire_competence').replaceWith(
        // ... with the returned one from the AJAX response.
        $(html).find('#requete_prestataire_competence')
        );
      // Position field now displays the appropriate positions.
    }
  });
});
</script>

如何使用客户端或爬虫从phpunit调用此代码?

我试过了 :

$this->client->request(
                'POST',
                '/',
                array('requete_prestataire[groupeCompetence]' =>2),
                array(),
                array(),
                array('HTTP_X-Requested-With' => 'XMLHttpRequest',
                    ));

但它不起作用。

非常感谢 !

ajax symfony testing web-scraping
1个回答
0
投票

我找到了解决方案:

您必须禁用验证,并在生成时发送表单:

$crawler = $this->client->request('GET', '/');

        $form = $crawler->selectButton('requete_prestataire_Rechercher')->form();
        $form['requete_prestataire[groupeCompetence]'] = 2;
        $form['requete_prestataire[competence]']->disableValidation()->select(50);

        $crawler = $this->client->submit($form);

这是doc中的解释:

doc symfony dom crawler component

© www.soinside.com 2019 - 2024. All rights reserved.