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

时间:2017-12-28 17:45:34

标签: ajax symfony testing web-scraping

我想测试一个生成页面的控制器,该页面的字段随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',
                    ));

但它没有用。

非常感谢!

1 个答案:

答案 0 :(得分: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